File tree 1 file changed +5
-19
lines changed
1 file changed +5
-19
lines changed Original file line number Diff line number Diff line change 1
- use std:: cmp;
2
-
3
1
/// Sorts a mutable slice using in-place insertion sort algorithm.
4
2
///
5
3
/// Time complexity is `O(n^2)`, where `n` is the number of elements.
6
4
/// 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 ] ) {
11
6
for i in 1 ..arr. len ( ) {
7
+ let mut j = i;
12
8
let cur = arr[ i] ;
13
- let mut j = i - 1 ;
14
9
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 ] ;
20
12
j -= 1 ;
21
13
}
22
14
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;
30
16
}
31
17
}
32
18
You can’t perform that action at this time.
0 commit comments