forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.rs
87 lines (76 loc) · 1.84 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::cmp::PartialOrd;
pub fn partition<T: PartialOrd>(arr: &mut [T], lo: isize, hi: isize) -> isize {
let pivot = hi as usize;
let mut i = lo - 1;
let mut j = hi;
loop {
i += 1;
while arr[i as usize] < arr[pivot] {
i += 1;
}
j -= 1;
while j >= 0 && arr[j as usize] > arr[pivot] {
j -= 1;
}
if i >= j {
break;
} else {
arr.swap(i as usize, j as usize);
}
}
arr.swap(i as usize, pivot);
i
}
fn _quick_sort<T: Ord>(arr: &mut [T], lo: isize, hi: isize) {
if lo < hi {
let p = partition(arr, lo, hi);
_quick_sort(arr, lo, p - 1);
_quick_sort(arr, p + 1, hi);
}
}
pub fn quick_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len > 1 {
_quick_sort(arr, 0, (len - 1) as isize);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let mut res = vec![10, 8, 4, 3, 1, 9, 2, 7, 5, 6];
quick_sort(&mut res);
assert_eq!(res, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}
#[test]
fn basic_string() {
let mut res = vec!["a", "bb", "d", "cc"];
quick_sort(&mut res);
assert_eq!(res, vec!["a", "bb", "cc", "d"]);
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
quick_sort(&mut res);
assert_eq!(res, vec![]);
}
#[test]
fn one_element() {
let mut res = vec![1];
quick_sort(&mut res);
assert_eq!(res, vec![1]);
}
#[test]
fn pre_sorted() {
let mut res = vec![1, 2, 3, 4];
quick_sort(&mut res);
assert_eq!(res, vec![1, 2, 3, 4]);
}
#[test]
fn reverse_sorted() {
let mut res = vec![4, 3, 2, 1];
quick_sort(&mut res);
assert_eq!(res, vec![1, 2, 3, 4]);
}
}