forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patience_sort.rs
82 lines (70 loc) · 1.79 KB
/
patience_sort.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::vec;
pub fn patience_sort<T: Ord + Copy>(arr: &mut [T]) {
if arr.is_empty() {
return;
}
// collect piles from arr
let mut piles: Vec<Vec<T>> = Vec::new();
for &card in arr.iter() {
let mut left = 0usize;
let mut right = piles.len();
while left < right {
let mid = left + (right - left) / 2;
if piles[mid][piles[mid].len() - 1] >= card {
right = mid;
} else {
left = mid + 1;
}
}
if left == piles.len() {
piles.push(vec![card]);
} else {
piles[left].push(card);
}
}
// merge the piles
let mut idx = 0usize;
while let Some((min_id, pile)) = piles
.iter()
.enumerate()
.min_by_key(|(_, pile)| *pile.last().unwrap())
{
arr[idx] = *pile.last().unwrap();
idx += 1;
piles[min_id].pop();
if piles[min_id].is_empty() {
_ = piles.remove(min_id);
}
}
}
#[cfg(test)]
mod tests {
use crate::sorting::is_sorted;
use super::*;
#[test]
fn basic() {
let mut array = vec![
-2, 7, 15, -14, 0, 15, 0, 100_33, 7, -7, -4, -13, 5, 8, -14, 12,
];
patience_sort(&mut array);
assert!(is_sorted(&array));
}
#[test]
fn empty() {
let mut array = Vec::<i32>::new();
patience_sort(&mut array);
assert!(is_sorted(&array));
}
#[test]
fn one_element() {
let mut array = vec![3];
patience_sort(&mut array);
assert!(is_sorted(&array));
}
#[test]
fn pre_sorted() {
let mut array = vec![-123_456, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
patience_sort(&mut array);
assert!(is_sorted(&array));
}
}