forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertion_sort.rs
71 lines (62 loc) · 1.55 KB
/
insertion_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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.swap(j + 1, j);
if j == 0 {
break;
}
j -= 1;
}
}
}
#[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));
}
}