Skip to content

Commit e8e1d22

Browse files
authored
Improve Insertion sort readability (#435)
1 parent 96d4e70 commit e8e1d22

File tree

1 file changed

+5
-19
lines changed

1 file changed

+5
-19
lines changed

src/sorting/insertion_sort.rs

+5-19
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,18 @@
1-
use std::cmp;
2-
31
/// Sorts a mutable slice using in-place insertion sort algorithm.
42
///
53
/// Time complexity is `O(n^2)`, where `n` is the number of elements.
64
/// Space complexity is `O(1)` as it sorts elements in-place.
7-
pub fn insertion_sort<T>(arr: &mut [T])
8-
where
9-
T: cmp::PartialOrd + Copy,
10-
{
5+
pub fn insertion_sort<T: Ord + Copy>(arr: &mut [T]) {
116
for i in 1..arr.len() {
7+
let mut j = i;
128
let cur = arr[i];
13-
let mut j = i - 1;
149

15-
while arr[j] > cur {
16-
arr[j + 1] = arr[j];
17-
if j == 0 {
18-
break;
19-
}
10+
while j > 0 && cur < arr[j - 1] {
11+
arr[j] = arr[j - 1];
2012
j -= 1;
2113
}
2214

23-
// we exit the loop from that break statement
24-
if j == 0 && arr[0] > cur {
25-
arr[0] = cur;
26-
} else {
27-
// `arr[j] > cur` is not satsified, exit from condition judgement
28-
arr[j + 1] = cur;
29-
}
15+
arr[j] = cur;
3016
}
3117
}
3218

0 commit comments

Comments
 (0)