Sorting algorithms/Heapsort: Difference between revisions

m (→‎{{header|VBA}}: fix formatting)
Line 3,415:
This program allows the caller to specify an arbitrary function by which an order is determined.
<lang rust>fn main() {
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
where F: Fn(&T, &T) -> bool ,
{
let len = array.len();
// Create heap
for start in (0..len / 2).rev() {
sift_downshift_down(array, &order, start, len - 1)
}
 
for end in (1..len).rev() {
array.swap(0, end);
sift_downshift_down(array, &order, 0, end - 1)
}
}
 
fn sift_downshift_down<T, F>(array: &mut [T], order: &F, start: usize, end: usize)
where
where F: Fn(&T, &T) -> bool,
{
let mut root = start;
loop {
let mut child = root * 2 + 1;
if child > end { break; }
break;
}
if child + 1 <= end && order(&array[child], &array[child + 1]) {
child += 1;
}
if order(&array[root], &array[child]) {
array.swap(root, child);
root = child
} else {
Line 3,459 ⟶ 3,463:
 
fn main() {
let src = vec![6, 2, 3, 6, 1, 2, 7, 8, 3, 2];
let sorted = BinaryHeap::from(src).into_sorted_vec();
println!("{:?}", sorted);
}</lang>
Anonymous user