forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell_sort.rs
52 lines (47 loc) · 1.55 KB
/
shell_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
pub fn shell_sort<T: Ord + Copy>(values: &mut Vec<T>) {
// shell sort works by swiping the value at a given gap and decreasing the gap to 1
fn insertion<T: Ord + Copy>(values: &mut Vec<T>, start: usize, gap: usize) {
for i in ((start + gap)..values.len()).step_by(gap) {
let val_current = values[i];
let mut pos = i;
// make swaps
while pos >= gap && values[pos - gap] > val_current {
values[pos] = values[pos - gap];
pos = pos - gap;
}
values[pos] = val_current;
}
}
let mut count_sublist = values.len() / 2; // makes gap as long as half of the array
while count_sublist > 0 {
for pos_start in 0..count_sublist {
insertion(values, pos_start, count_sublist);
}
count_sublist /= 2; // makes gap as half of previous
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn shell_sort_test() {
// test for reverse array
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
shell_sort(&mut ve1);
for i in 0..ve1.len() - 1 {
assert!(ve1[i] <= ve1[i + 1]);
}
// test for already sorted array
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
shell_sort(&mut ve2);
for i in 0..ve2.len() - 1 {
assert!(ve2[i] <= ve2[i + 1]);
}
// test for unsorted
let mut ve3 = vec![3, 5, 6, 3, 1, 4];
shell_sort(&mut ve3);
for i in 0..ve3.len() - 1 {
assert!(ve3[i] <= ve3[i + 1]);
}
}
}