forked from alexfertel/rust-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comb_sort.rs
46 lines (39 loc) · 910 Bytes
/
comb_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
use crate::sorting::traits::Sorter;
fn comb_sort<T: Ord>(arr: &mut [T]) {
let mut gap = arr.len();
if gap <= 1 {
return;
}
let shrink = 1.3;
let mut sorted = false;
while !sorted {
gap = (gap as f32 / shrink).floor() as usize;
if gap <= 1 {
gap = 1;
sorted = true;
}
for i in 0..arr.len() - gap {
let j = i + gap;
if arr[i] > arr[j] {
arr.swap(i, j);
sorted = false;
}
}
}
}
pub struct CombSort;
impl<T> Sorter<T> for CombSort
where
T: Ord + Copy,
{
fn sort_inplace(arr: &mut [T]) {
comb_sort(arr);
}
}
#[cfg(test)]
mod tests {
use crate::sorting::traits::Sorter;
use crate::sorting::CombSort;
sorting_tests!(CombSort::sort, comb_sort);
sorting_tests!(CombSort::sort_inplace, comb_sort, inplace);
}