Skip to content

Commit

Permalink
sort: Add benchmark for inplace shell merge sort
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Jul 4, 2024
1 parent 758b94e commit dfee60f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
15 changes: 10 additions & 5 deletions sort/benches/merge_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@

use std::time::Duration;

use criterion::{criterion_group, criterion_main, Criterion};
use criterion::{Criterion, criterion_group, criterion_main};

use sort::merge_sort::{
bottom_up_merge_sort, in_place_merge_sort, insertion_merge_sort, shell_merge_sort,
three_way_merge_sort, topdown_merge_sort,
};
use sort::merge_sort::{bottom_up_merge_sort, in_place_merge_sort, in_place_shell_merge_sort, insertion_merge_sort, shell_merge_sort, three_way_merge_sort, topdown_merge_sort};
use sort::util::random_ints;

fn criterion_benchmark(c: &mut Criterion) {
Expand All @@ -23,6 +20,7 @@ fn criterion_benchmark(c: &mut Criterion) {
let title5 = format!("bottom_up_merge_sort {len}");
let title6 = format!("three_way_merge_sort {len}");
let title7 = format!("in_place_merge_sort {len}");
let title8 = format!("in_place_shell_merge_sort {len}");
let mut arr_sorted = arr.clone();
arr_sorted.sort();

Expand Down Expand Up @@ -75,6 +73,13 @@ fn criterion_benchmark(c: &mut Criterion) {
assert_eq!(arr7, arr_sorted);
})
});
c.bench_function(&title8, |b| {
b.iter(|| {
let mut arr8 = arr.clone();
in_place_shell_merge_sort(&mut arr8);
assert_eq!(arr8, arr_sorted);
})
});
}
}

Expand Down
1 change: 1 addition & 0 deletions sort/src/merge_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ where
while gap > 0 {
for i in low..=(high - gap) {
let j = i + gap;
// 每次间隔多个元素进行比较和交换.
if arr[i] > arr[j] {
arr.swap(i, j);
}
Expand Down
10 changes: 5 additions & 5 deletions src/sort/merge-sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
{{#include assets/merge_sort.rs:15:76}}
```

## 归并排序的特点

- 归并排序的时间复杂度是 `O(N log(N))`, 空间复杂度是 `O(N)`

## 元素较少时, 使用插入排序

在排序阶段, 如果数组元素较少时仍然使用递归的归并排序的话, 并不划算, 因为会有大量的递归分支被调用,
Expand Down Expand Up @@ -109,11 +113,7 @@
移动元素的次数.

```rust
{{#include assets/merge_sort.rs:427:476}}
{{#include assets/merge_sort.rs:427:485}}
```

- 时间复杂度度是 `O(N Log(N) Log(N))`, 空间复杂度是 `O(1)`

## 归并排序的特点

- 归并排序的时间复杂度是 `O(N log(N))`, 空间复杂度是 `O(N)`

0 comments on commit dfee60f

Please sign in to comment.