-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquick_sort.rs
57 lines (50 loc) · 1.48 KB
/
quick_sort.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use rand::Rng;
/// Generate random pivot index using start and end indices
fn rand_pivot(start: usize, end: usize) -> usize {
rand::thread_rng().gen_range(start, end)
}
/// Partition vector of distinct integers (partially sort using endpoint indices)
fn partition(x: &mut [isize], left: usize, right: usize) -> usize {
let pivot_value = x[left];
let mut i = left + 1;
for j in i..right {
if x[j] < pivot_value {
x.swap(j, i);
i += 1;
}
}
let pivot = i - 1;
x.swap(left, pivot);
pivot
}
/// Quick Sort implementation
fn quick_sort(x: &mut [isize], left: usize, right: usize) {
if left >= right { return }
let mut pivot = rand_pivot(left, right);
x.swap(left, pivot);
pivot = partition(x, left, right);
quick_sort(x, left, pivot);
quick_sort(x, pivot + 1, right);
}
/// Quick Sort
///
/// Input: vector x of n distinct integers, left and right endpoint indices
/// Post-condition: sorted vector of n elements
///
/// ================================================================================================
///
/// if length of x equals or is less than 1 then
/// base case: return
///
/// pivot index = random pivot index from x
/// swap x[left] for x[pivot index]
/// j = partition vector x (partial sort)
///
/// recursive sort:
/// x, left, j
/// x, j + 1, right
pub fn sort(x: &mut Vec<isize>) {
let left = 0;
let right = x.len();
quick_sort(x.as_mut_slice(), left, right);
}