September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -1,46 +1,39 @@
|
|||
// Type alias for function that returns true if arguments should be swapped
|
||||
type OrderFunc<T> = Fn(&T, &T) -> bool;
|
||||
|
||||
fn main() {
|
||||
// Sort numbers
|
||||
println!("Sort numbers in descending order");
|
||||
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
|
||||
println!("Before: {:?}", numbers);
|
||||
|
||||
quick_sort(&mut numbers, &is_less);
|
||||
println!("After: {:?}", numbers);
|
||||
quick_sort(&mut numbers, &|x,y| x > y);
|
||||
println!("After: {:?}\n", numbers);
|
||||
|
||||
// Sort strings
|
||||
println!("Sort strings alphabetically");
|
||||
let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"];
|
||||
println!("Before: {:?}", strings);
|
||||
|
||||
quick_sort(&mut strings, &is_less);
|
||||
println!("After: {:?}", strings);
|
||||
quick_sort(&mut strings, &|x,y| x < y);
|
||||
println!("After: {:?}\n", strings);
|
||||
|
||||
println!("Sort strings by length");
|
||||
println!("Before: {:?}", strings);
|
||||
|
||||
quick_sort(&mut strings, &|x,y| x.len() < y.len());
|
||||
println!("After: {:?}", strings);
|
||||
}
|
||||
|
||||
|
||||
// Example OrderFunc which is used to order items from least to greatest
|
||||
#[inline(always)]
|
||||
fn is_less<T: Ord>(x: &T, y: &T) -> bool {
|
||||
x < y
|
||||
}
|
||||
|
||||
fn quick_sort<T>(v: &mut [T], f: &OrderFunc<T>) {
|
||||
|
||||
fn quick_sort<T,F>(v: &mut [T], f: &F)
|
||||
where F: Fn(&T,&T) -> bool
|
||||
{
|
||||
let len = v.len();
|
||||
if len < 2 {
|
||||
return;
|
||||
if len >= 2 {
|
||||
let pivot_index = partition(v, f);
|
||||
quick_sort(&mut v[0..pivot_index], f);
|
||||
quick_sort(&mut v[pivot_index + 1..len], f);
|
||||
}
|
||||
|
||||
let pivot_index = partition(v, f);
|
||||
|
||||
// Sort the left side
|
||||
quick_sort(&mut v[0..pivot_index], f);
|
||||
|
||||
// Sort the right side
|
||||
quick_sort(&mut v[pivot_index + 1..len], f);
|
||||
}
|
||||
|
||||
fn partition<T>(v: &mut [T], f: &OrderFunc<T>) -> usize {
|
||||
fn partition<T,F>(v: &mut [T], f: &F) -> usize
|
||||
where F: Fn(&T,&T) -> bool
|
||||
{
|
||||
let len = v.len();
|
||||
let pivot_index = len / 2;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue