June 2018 Update

This commit is contained in:
Ingy döt Net 2018-06-22 20:57:24 +00:00
parent ba8067c3b7
commit 22f33d4004
5278 changed files with 84726 additions and 14379 deletions

View file

@ -1,36 +1,40 @@
fn main() {
let mut v = [4,6,8,1,0,3,2,2,9,5];
heap_sort(&mut v, |x,y| x < y);
let mut v = [4, 6, 8, 1, 0, 3, 2, 2, 9, 5];
heap_sort(&mut v, |x, y| x < y);
println!("{:?}", v);
}
fn heap_sort<T,F>(array: &mut [T], order: F)
where F: Fn(&T,&T) -> bool
fn heap_sort<T, F>(array: &mut [T], order: F)
where
F: Fn(&T, &T) -> bool,
{
let len = array.len();
// Create heap
for start in (0..len/2).rev() {
sift_down(array,&order,start,len-1)
for start in (0..len / 2).rev() {
shift_down(array, &order, start, len - 1)
}
for end in (1..len).rev() {
array.swap(0,end);
sift_down(array,&order,0,end-1)
array.swap(0, end);
shift_down(array, &order, 0, end - 1)
}
}
fn sift_down<T,F>(array: &mut [T], order: &F, start: usize, end: usize)
where F: Fn(&T,&T) -> bool
fn shift_down<T, F>(array: &mut [T], order: &F, start: usize, end: usize)
where
F: Fn(&T, &T) -> bool,
{
let mut root = start;
loop {
let mut child = root * 2 + 1;
if child > end { break; }
if child > end {
break;
}
if child + 1 <= end && order(&array[child], &array[child + 1]) {
child += 1;
}
if order(&array[root], &array[child]) {
array.swap(root,child);
array.swap(root, child);
root = child
} else {
break;

View file

@ -1,7 +1,7 @@
use std::collections::BinaryHeap;
fn main() {
let src = vec![6,2,3,6,1,2,7,8,3,2];
let sorted= BinaryHeap::from(src).into_sorted_vec();
let src = vec![6, 2, 3, 6, 1, 2, 7, 8, 3, 2];
let sorted = BinaryHeap::from(src).into_sorted_vec();
println!("{:?}", sorted);
}