forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gnome_sort.rs
60 lines (52 loc) · 1.19 KB
/
gnome_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 gnome_sort<T>(arr: &[T]) -> Vec<T>
where
T: cmp::PartialEq + cmp::PartialOrd + Clone,
{
let mut arr = arr.to_vec();
let mut i: usize = 1;
let mut j: usize = 2;
while i < arr.len() {
if arr[i - 1] < arr[i] {
i = j;
j = i + 1;
} else {
arr.swap(i - 1, i);
i -= 1;
if i == 0 {
i = j;
j += 1;
}
}
}
arr
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let res = gnome_sort(&vec![6, 5, -8, 3, 2, 3]);
assert_eq!(res, vec![-8, 2, 3, 3, 5, 6]);
}
#[test]
fn already_sorted() {
let res = gnome_sort(&vec!["a", "b", "c"]);
assert_eq!(res, vec!["a", "b", "c"]);
}
#[test]
fn odd_number_of_elements() {
let res = gnome_sort(&vec!["d", "a", "c", "e", "b"]);
assert_eq!(res, vec!["a", "b", "c", "d", "e"]);
}
#[test]
fn one_element() {
let res = gnome_sort(&vec![3]);
assert_eq!(res, vec![3]);
}
#[test]
fn empty() {
let res = gnome_sort(&Vec::<u8>::new());
assert_eq!(res, vec![]);
}
}