1
1
impl Solution {
2
- pub fn sort_array ( num : Vec < i32 > ) -> Vec < i32 > {
3
- return vec ! [ ] ;
4
- }
5
-
6
- fn quick_sort ( num : & Vec < i32 > ) -> & Vec < i32 > {
7
- if num. len ( ) < 1 {
8
- return & vec ! [ ] ;
9
- }
10
- if num. len ( ) == 1 {
11
- return num;
2
+ fn quick_sort ( nums : & mut [ i32 ] , left : isize , right : isize ) {
3
+ if left <= right { // 1
4
+ let mid = Solution :: partition ( nums, left, right) ; // 2
5
+ Solution :: quick_sort ( nums, left, mid - 1 ) ; // 3
6
+ Solution :: quick_sort ( nums, mid + 1 , right) ; // 4
12
7
}
13
- let mid = Solution :: partition ( & num, 0 , num. len ( ) - 1 ) ;
14
- let left_slice = Solution :: quick_sort ( num[ ..mid] ) ;
15
- let right_slice = Solution :: quick_sort ( num[ mid+1 ..] ) ;
16
- let temp = [ left_slice, vec ! [ num[ mid] ] , right_slice] . concat ( ) ;
17
- return temp;
18
8
}
19
9
20
- fn partition ( num : & Vec < i32 > , left : usize , right : usize ) -> usize {
21
- let pivot = num[ right] ;
22
- let i = left;
23
- for j in left .. right {
24
- if num[ j] > pivot {
25
- Solution :: swap_here ( num, i, j) ;
26
- i += 1 ;
10
+ fn partition ( arr : & mut [ i32 ] , lo : isize , hi : isize ) -> isize {
11
+ // -- Determine the pivot --
12
+ // In Lomuto parition scheme,
13
+ // the latest element is always chosen as the pivot.
14
+ let pivot = arr[ hi as usize ] ; // 1
15
+ let mut i = lo;
16
+
17
+ // -- Swap elements --
18
+ for j in lo..hi { // 2
19
+ if arr[ j as usize ] < pivot {
20
+ arr. swap ( i as usize , j as usize ) ;
21
+ i += 1 ; // 3
27
22
}
28
23
}
29
- Solution :: swap_here ( num, i, right) ;
30
- return i;
31
- }
32
-
33
- fn swap_here ( num : & Vec < i32 > , x : usize , y : usize ) {
34
- let temp = num[ x] ;
35
- num[ x] = num[ y] ;
36
- num[ y] = temp;
24
+ // Swap pivot to the middle of two piles.
25
+ arr. swap ( i as usize , hi as usize ) ; // 4
26
+ i // Return the final index of the pivot
37
27
}
38
28
}
39
29
struct Solution {
40
30
41
31
}
42
32
43
33
fn main ( ) {
44
-
34
+ let mut list = [ 1 , 5 , 2 , 35 , 6 , 0 , -4 , 2 , 123 , 45 , 652 ] ;
35
+ Solution :: quick_sort ( & mut list, 0 , 10 ) ;
36
+ println ! ( "{:?}" , list) ;
45
37
}
0 commit comments