Ai
2 Star 1 Fork 0

endpoint_rust/Rust

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
insertion_sort.rs 1.80 KB
一键复制 编辑 原始数据 按行查看 历史
SteveLau 提交于 2022-07-30 16:26 +08:00 . #349: improve performance of insertion sort (#350)
use std::cmp;
/// Sorts a mutable slice using in-place insertion sort algorithm.
///
/// Time complexity is `O(n^2)`, where `n` is the number of elements.
/// Space complexity is `O(1)` as it sorts elements in-place.
pub fn insertion_sort<T>(arr: &mut [T])
where
T: cmp::PartialOrd + Copy,
{
for i in 1..arr.len() {
let cur = arr[i];
let mut j = i - 1;
while arr[j] > cur {
arr[j + 1] = arr[j];
if j == 0 {
break;
}
j -= 1;
}
// we exit the loop from that break statement
if j == 0 && arr[0] > cur {
arr[0] = cur;
} else {
// `arr[j] > cur` is not satsified, exit from condition judgement
arr[j + 1] = cur;
}
}
}
#[cfg(test)]
mod tests {
use super::super::is_sorted;
use super::*;
#[test]
fn empty() {
let mut arr: [u8; 0] = [];
insertion_sort(&mut arr);
assert!(is_sorted(&arr));
}
#[test]
fn one_element() {
let mut arr: [char; 1] = ['a'];
insertion_sort(&mut arr);
assert!(is_sorted(&arr));
}
#[test]
fn already_sorted() {
let mut arr: [&str; 3] = ["a", "b", "c"];
insertion_sort(&mut arr);
assert!(is_sorted(&arr));
}
#[test]
fn basic() {
let mut arr: [&str; 4] = ["d", "a", "c", "b"];
insertion_sort(&mut arr);
assert!(is_sorted(&arr));
}
#[test]
fn odd_number_of_elements() {
let mut arr: Vec<&str> = vec!["d", "a", "c", "e", "b"];
insertion_sort(&mut arr);
assert!(is_sorted(&arr));
}
#[test]
fn repeated_elements() {
let mut arr: Vec<usize> = vec![542, 542, 542, 542];
insertion_sort(&mut arr);
assert!(is_sorted(&arr));
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Rust
1
https://gitee.com/endpoint_rust/Rust.git
git@gitee.com:endpoint_rust/Rust.git
endpoint_rust
Rust
Rust
master

搜索帮助