Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -1,32 +1,58 @@
// Type alias for function that returns true if arguments are in the correct order
type OrderFunc<T> = Fn(&T, &T) -> bool;
fn main() {
// Sort numbers
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {:?}", numbers);
quick_sort(&mut numbers, &f);
println!("After: {:?}", numbers);
// Sort strings
let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"];
println!("Before: {:?}", strings);
quick_sort(&mut strings, &f);
println!("After: {:?}", strings);
}
// Example OrderFunc which is used to order items from least to greatest
#[inline]
fn f<T: Ord>(x: &T, y: &T) -> bool {
x < y
}
// We use in place quick sort
// For details see http://en.wikipedia.org/wiki/Quicksort#In-place_version
fn quick_sort<T: Ord>(v: &mut[T]) {
fn quick_sort<T>(v: &mut [T], f: &OrderFunc<T>) {
let len = v.len();
if len < 2 {
return;
}
let pivot_index = partition(v);
let pivot_index = partition(v, f);
// Sort the left side
quick_sort(v.mut_slice(0, pivot_index));
quick_sort(&mut v[0..pivot_index], f);
// Sort the right side
quick_sort(v.mut_slice(pivot_index + 1, len));
quick_sort(&mut v[pivot_index + 1..len], f);
}
// Reorders the slice with values lower than the pivot at the left side,
// and values bigger than it at the right side.
// Also returns the store index.
fn partition<T: Ord>(v: &mut [T]) -> uint {
fn partition<T>(v: &mut [T], f: &OrderFunc<T>) -> usize {
let len = v.len();
let pivot_index = len / 2;
v.swap(pivot_index, len - 1);
let mut store_index = 0;
for i in range(0, len - 1) {
if v[i] <= v[len - 1] {
for i in 0..len - 1 {
if f(&v[i], &v[len - 1]) {
v.swap(i, store_index);
store_index += 1;
}
@ -35,19 +61,3 @@ fn partition<T: Ord>(v: &mut [T]) -> uint {
v.swap(store_index, len - 1);
store_index
}
fn main() {
// Sort numbers
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {}", numbers.as_slice());
quick_sort(numbers);
println!("After: {}", numbers.as_slice());
// Sort strings
let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"];
println!("Before: {}", strings.as_slice());
quick_sort(strings);
println!("After: {}", strings.as_slice());
}