Skip to content

Commit

Permalink
feat(binary_sort): 增加二分排序
Browse files Browse the repository at this point in the history
  • Loading branch information
donjuanplatinum committed Jun 24, 2024
1 parent 88a4c4e commit e40cfa7
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
- [InsertionSort 插入排序](./doc/sorting/_index.md)
- [SelectionSort 选择排序](./doc/sorting/_index.md)
- [BubbleSort 冒泡排序](./doc/sorting/_index.md)
- [BinarySort 二分排序](./doc/sorting/_index.md)
### Structures 数据结构
- [Heap 堆/优先队列](./doc/structure/_index.md)
### Searching 搜索
Expand Down
5 changes: 5 additions & 0 deletions doc/sorting/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ math: true
| 插入排序 | 稳定 | $ \Theta( n ^ 2) $ | $ \Theta( n ^ 2) $ | O(1) |
| 选择排序 | 不稳定 | $ \Theta( n ^ 2) $ | $ \Theta( n ^ 2) $ | O(1) |
| 冒泡排序 | 稳定 | $ O( n ^ 2 ) $ | $ O( n ^ 2 ) $ | O(1) |
| 二分排序 | 稳定 | $ \Theta( n ^ 2) $ | $ \Theta( n ^ 2) $ | O(1) |



Expand Down Expand Up @@ -39,3 +40,7 @@ math: true
[![Bubble_Sort](./bubble_sort.gif)](./bubble_sort.gif)

## 二分排序
对插入排序的二分优化

将插入点的寻找替换为二分查找 从0开始到的point的序列是有序的
54 changes: 54 additions & 0 deletions src/sorting/insertion_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,35 @@ pub fn insertion_sort<T>(array: &mut [T], comparator: fn(&T, &T) -> bool) -> ()
}
}

use crate::searching::binary_search;
/// Binary Sort
/// # Example
/// ```
/// use algori::sorting::{binary_sort,is_sorted};
/// let mut a = [2,3,1,34,15,8,0,7,4,3,21,4,6,7,4,2341,321,41231,312,62];
/// binary_sort(&mut a);
/// is_sorted(&mut a,|a,b| a<=b);
/// ```
pub fn binary_sort<T: PartialOrd>(array: &mut [T]) -> () {
for point in 1..array.len() {
let mut current_point: usize = point;
match binary_search(&array[0..point], &array[point]) {
Ok(index) => {
while current_point > index {
array.swap(current_point, current_point - 1);
current_point -= 1;
}
}
Err(index) => {
while current_point > index {
array.swap(current_point, current_point - 1);
current_point -= 1;
}
}
}
}
}

#[cfg(test)]
mod insertion_sort_tests {
use super::super::is_sorted;
Expand Down Expand Up @@ -47,3 +76,28 @@ mod insertion_sort_tests {
assert_eq!(is_sorted(&mut a, |a, b| a >= b), true);
}
}

mod binary_sort_tests {
use super::super::is_sorted;
use super::binary_sort;
#[test]
fn empty() -> () {
let mut a: [i32; 0] = [];
binary_sort(&mut a);

assert_eq!(is_sorted(&mut a, |a, b| a <= b), true);
}

#[test]
fn one_element() -> () {
let mut a: [i32; 1] = [1];
binary_sort(&mut a);
assert_eq!(is_sorted(&mut a, |a, b| a <= b), true);
}
#[test]
fn positive() -> () {
let mut a = [1, 123, 123, 12, 4234, 42, 1123, 123, 15112, 312];
binary_sort(&mut a);
assert_eq!(is_sorted(&mut a, |a, b| a <= b), true);
}
}

0 comments on commit e40cfa7

Please sign in to comment.