forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pancake_sort.rs
60 lines (53 loc) · 1.31 KB
/
pancake_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
use std::cmp;
pub fn pancake_sort<T>(arr: &mut [T]) -> Vec<T>
where
T: cmp::PartialEq + cmp::Ord + cmp::PartialOrd + Clone,
{
let len = arr.len();
if len < 2 {
arr.to_vec();
}
for i in (0..len).rev() {
let max_index = arr
.iter()
.take(i + 1)
.enumerate()
.max_by_key(|&(_, elem)| elem)
.map(|(idx, _)| idx)
.unwrap();
if max_index != i {
arr[0..max_index + 1].reverse();
arr[0..i + 1].reverse();
}
}
arr.to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let res = pancake_sort(&mut vec![6, 5, -8, 3, 2, 3]);
assert_eq!(res, vec![-8, 2, 3, 3, 5, 6]);
}
#[test]
fn already_sorted() {
let res = pancake_sort(&mut vec!["a", "b", "c"]);
assert_eq!(res, vec!["a", "b", "c"]);
}
#[test]
fn odd_number_of_elements() {
let res = pancake_sort(&mut vec!["d", "a", "c", "e", "b"]);
assert_eq!(res, vec!["a", "b", "c", "d", "e"]);
}
#[test]
fn one_element() {
let res = pancake_sort(&mut vec![3]);
assert_eq!(res, vec![3]);
}
#[test]
fn empty() {
let res = pancake_sort(&mut Vec::<u8>::new());
assert_eq!(res, vec![]);
}
}