forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
insertion_sort.rs
65 lines (56 loc) · 1.49 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
/// 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: Ord + Copy>(arr: &mut [T]) {
for i in 1..arr.len() {
let mut j = i;
let cur = arr[i];
while j > 0 && cur < arr[j - 1] {
arr[j] = arr[j - 1];
j -= 1;
}
arr[j] = 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));
}
}