pub fn quick_sort<T: PartialOrd>(arr: &mut [T]) {
let len = arr.len();
if len > 1 {
quick_sort_range(arr, 0, len - 1);
}
}
fn quick_sort_range<T: PartialOrd>(arr: &mut[T], low: usize, high:usize) {
if low < high {
let partition = partition(arr, low, high);
if partition > 0 {
quick_sort_range(arr, low, partition);
}
quick_sort_range(arr, partition + 1, high)
}
}
fn partition<T: PartialOrd>(arr: &mut [T], low: usize, high: usize) -> usize {
use rand::Rng;
let r = rand::thread_rng().gen_range(low..=high);
arr.swap(low, r);
let (
pivot,
mut left,
mut right
) = (
low,
low,
high
);
while left < right {
while left < right && arr[right] > arr[pivot] {
right -= 1;
}
while left < right && arr[left] <= arr[pivot] {
left += 1;
}
if left != right {
arr.swap(left, right);
}
}
arr.swap(pivot, left);
left
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結