Skip to content

Instantly share code, notes, and snippets.

@aita
Last active January 2, 2020 10:17
Show Gist options
  • Select an option

  • Save aita/992b99921ba9e55acb9189417a169df9 to your computer and use it in GitHub Desktop.

Select an option

Save aita/992b99921ba9e55acb9189417a169df9 to your computer and use it in GitHub Desktop.
fn heapify<T: PartialOrd>(v: &mut [T], i: usize) {
let len = v.len();
let mut j = i;
let mut max = i;
loop {
let l = j * 2 + 1;
let r = j * 2 + 2;
if l < len && v[l] > v[max] {
max = l;
}
if r < len && v[r] > v[max] {
max = r;
}
if max == j {
break;
}
v.swap(j, max);
j = max;
}
}
fn heap_sort<T: PartialOrd>(v: &mut [T]) {
let len = v.len();
for i in (0..(len - 1) / 2 + 1).rev() {
heapify(v, i);
}
for i in (0..len).rev() {
v.swap(0, i);
heapify(&mut v[0..i], 0);
}
}
fn main() {
let mut v = [5, 1, 4, 2, 6, 3];
heap_sort(&mut v);
println!("{:?}", v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment