Skip to content

Commit a815580

Browse files
author
quintanamo
committed
clean up insertion sort and add tests
1 parent 5726fce commit a815580

File tree

1 file changed

+43
-6
lines changed

1 file changed

+43
-6
lines changed

src/sorting.rs

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
11
pub fn insertion_sort(input: Vec<i32>) -> Vec<i32> {
22
let mut sorted: Vec<i32> = input;
33

4-
for j in 1..sorted.len() as i32 {
5-
let key: i32 = sorted[j as usize];
6-
let mut i: i32 = j - 1;
7-
while i >= 0 && sorted[i as usize] > key {
8-
sorted[(i + 1) as usize] = sorted[i as usize];
4+
for j in 1..sorted.len() {
5+
let key: i32 = sorted[j];
6+
let mut i: usize = j;
7+
while i > 0 && sorted[i - 1] > key {
8+
sorted[i] = sorted[i - 1];
99
i = i - 1;
1010
}
11-
sorted[(i + 1) as usize] = key;
11+
sorted[i] = key;
1212
}
1313

1414
return sorted;
15+
}
16+
17+
fn is_sorted(input: Vec<i32>) -> bool {
18+
let mut last_num = 0;
19+
for num in input {
20+
if num < last_num {
21+
return false;
22+
}
23+
last_num = num;
24+
}
25+
return true;
26+
}
27+
28+
#[cfg(test)]
29+
mod tests {
30+
use super::insertion_sort;
31+
use super::is_sorted;
32+
33+
#[test]
34+
fn test_is_sorted() {
35+
let mut input: Vec<i32> = [5,2,3,1,4].to_vec();
36+
assert_eq!(is_sorted(input), false);
37+
input = [1, 2, 3, 4, 5].to_vec();
38+
assert_eq!(is_sorted(input), true);
39+
input = [1, 1, 2, 2, 3].to_vec();
40+
assert_eq!(is_sorted(input), true);
41+
}
42+
43+
#[test]
44+
fn test_insertion_sort() {
45+
let mut input: Vec<i32> = [5,2,3,1,4].to_vec();
46+
let mut output: Vec<i32> = insertion_sort(input);
47+
assert_eq!(is_sorted(output), true);
48+
input = [1, 1, 2, 1, 1].to_vec();
49+
output = insertion_sort(input);
50+
assert_eq!(is_sorted(output), true);
51+
}
1552
}

0 commit comments

Comments
 (0)