Skip to content

Commit 5a833f4

Browse files
author
wuyinjun.oreki
committed
quick sort rust
1 parent 005915d commit 5a833f4

File tree

1 file changed

+23
-31
lines changed

1 file changed

+23
-31
lines changed

快速排序/main.rs

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,37 @@
11
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
127
}
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;
188
}
199

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
2722
}
2823
}
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
3727
}
3828
}
3929
struct Solution {
4030

4131
}
4232

4333
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);
4537
}

0 commit comments

Comments
 (0)