Sorting algorithms/Heapsort: Difference between revisions

Content added Content deleted
(→‎{{header|Rust}}: Actually using a vector is unnecessary)
Line 3,361: Line 3,361:
{{trans|Python}}
{{trans|Python}}
This program allows the caller to specify an arbitrary function by which an order is determined.
This program allows the caller to specify an arbitrary function by which an order is determined.
<lang rust>use std::mem;
<lang rust>fn main() {

fn main() {
let mut v = [4,6,8,1,0,3,2,2,9,5];
let mut v = [4,6,8,1,0,3,2,2,9,5];
heap_sort(&mut v, |x,y| x < y);
heap_sort(&mut v, |x,y| x < y);
Line 3,379: Line 3,377:


for end in (1..len).rev() {
for end in (1..len).rev() {
{
array.swap(0,end);
let (b,e) = array.split_at_mut(1);
mem::swap(&mut b[0], &mut e[end-1]);
}
sift_down(array,&order,0,end-1)
sift_down(array,&order,0,end-1)
}
}
Line 3,398: Line 3,393:
}
}
if order(&array[root], &array[child]) {
if order(&array[root], &array[child]) {
let (r,c) = array.split_at_mut(child);
array.swap(root,child);
mem::swap(&mut r[root], &mut c[0]);
root = child
root = child
} else {
} else {
Line 3,405: Line 3,399:
}
}
}
}
}</lang>

Of course, you could also simply use <code>BinaryHeap</code> in the standard library.

<lang rust>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();
println!("{:?}", sorted);
}</lang>
}</lang>