forked from alexfertel/rust-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.rs
64 lines (56 loc) · 1.8 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
use crate::sorting::traits::Sorter;
fn quick_sort<T: Ord>(array: &mut [T]) {
match array.len() {
0 | 1 => return,
_ => {}
}
let (pivot, rest) = array.split_first_mut().expect("array is non-empty");
let mut left = 0;
let mut right = rest.len() - 1;
while left <= right {
if &rest[left] <= pivot {
left += 1;
} else if &rest[right] > pivot {
if right == 0 {
break;
}
right -= 1;
} else {
rest.swap(left, right);
left += 1;
if right == 0 {
break;
}
right -= 1;
}
}
array.swap(0, left);
let (left, right) = array.split_at_mut(left);
quick_sort(left);
quick_sort(&mut right[1..]);
}
/// QuickSort is a Divide and Conquer algorithm. It picks an element as
/// a pivot and partitions the given array around the picked pivot.
/// There are many different versions of quickSort that pick pivot in different ways.
/// parameters takes an array
/// The key process in quickSort is a partition().
/// The target of partitions is, given an array and an element x of an array as the pivot,
/// put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x,
/// and put all greater elements (greater than x) after x. All this should be done in linear time.
/// Quicksort's time complexity is O(n*logn) .
pub struct QuickSort;
impl<T> Sorter<T> for QuickSort
where
T: Ord + Copy,
{
fn sort_inplace(array: &mut [T]) {
quick_sort(array);
}
}
#[cfg(test)]
mod tests {
use crate::sorting::traits::Sorter;
use crate::sorting::QuickSort;
sorting_tests!(QuickSort::sort, quick_sort);
sorting_tests!(QuickSort::sort_inplace, quick_sort, inplace);
}