forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
odd_even_sort.rs
58 lines (50 loc) · 1.19 KB
/
odd_even_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
pub fn odd_even_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len == 0 {
return;
}
let mut sorted = false;
while !sorted {
sorted = true;
for i in (1..len - 1).step_by(2) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
for i in (0..len - 1).step_by(2) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let mut arr = vec![3, 5, 1, 2, 4, 6];
odd_even_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5, 6]);
}
#[test]
fn empty() {
let mut arr = Vec::<i32>::new();
odd_even_sort(&mut arr);
assert_eq!(arr, vec![]);
}
#[test]
fn one_element() {
let mut arr = vec![3];
odd_even_sort(&mut arr);
assert_eq!(arr, vec![3]);
}
#[test]
fn pre_sorted() {
let mut arr = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
odd_even_sort(&mut arr);
assert_eq!(arr, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
}