Skip to content

Commit 0861a69

Browse files
Wafelackimp2002
andauthored
feat: add comb sort (rust-lang#231)
* Add comb sort * Add comb sort to README. Co-authored-by: imp <imp07@qq.com>
1 parent 78f5c22 commit 0861a69

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ RESTART BUILD
2020
- [x] [Selection](./src/sorting/selection_sort.rs)
2121
- [x] [Shell](./src/sorting/shell_sort.rs)
2222
- [x] [Stooge](./src/sorting/stooge_sort.rs)
23+
- [x] [Comb](./src/sorting/comb_sort.rs)
2324

2425
## Graphs
2526

src/sorting/comb_sort.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
pub fn comb_sort<T: Ord>(arr: &mut [T]) {
2+
let mut gap = arr.len();
3+
let shrink = 1.3;
4+
let mut sorted = false;
5+
6+
while !sorted {
7+
gap = (gap as f32 / shrink).floor() as usize;
8+
if gap <= 1 {
9+
gap = 1;
10+
sorted = true;
11+
}
12+
for i in 0..arr.len() - gap {
13+
let j = i + gap;
14+
if arr[i] > arr[j] {
15+
arr.swap(i, j);
16+
sorted = false;
17+
}
18+
}
19+
}
20+
}
21+
22+
#[cfg(test)]
23+
mod tests {
24+
use super::*;
25+
26+
#[test]
27+
fn descending() {
28+
//descending
29+
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
30+
comb_sort(&mut ve1);
31+
for i in 0..ve1.len() - 1 {
32+
assert!(ve1[i] <= ve1[i + 1]);
33+
}
34+
}
35+
36+
#[test]
37+
fn ascending() {
38+
//pre-sorted
39+
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
40+
comb_sort(&mut ve2);
41+
for i in 0..ve2.len() - 1 {
42+
assert!(ve2[i] <= ve2[i + 1]);
43+
}
44+
}
45+
}

src/sorting/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
mod bubble_sort;
22
mod cocktail_shaker_sort;
3+
mod comb_sort;
34
mod counting_sort;
45
mod heap_sort;
56
mod insertion_sort;
@@ -13,6 +14,7 @@ mod stooge_sort;
1314

1415
pub use self::bubble_sort::bubble_sort;
1516
pub use self::cocktail_shaker_sort::cocktail_shaker_sort;
17+
pub use self::comb_sort::comb_sort;
1618
pub use self::counting_sort::counting_sort;
1719
pub use self::counting_sort::generic_counting_sort;
1820
pub use self::heap_sort::heap_sort;

0 commit comments

Comments
 (0)