1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use super::signature::*;
pub struct Heap;
impl Heap {
fn heapify<T: Sortable>(&self, list: &mut Vec<T>) {
let smallest_parent: usize = list.len() / 2;
let end = list.len() - 1;
for i in (0..smallest_parent + 1).rev() {
self.sift_down(list, i, end);
}
}
fn sift_down<T: Sortable>(&self, list: &mut Vec<T>, start: usize, end: usize) {
let mut root = start;
while 2 * root <= end {
let left_child = 2 * root;
let mut swap = root;
if list[swap] < list[left_child] {
swap = left_child;
}
if left_child + 1 <= end && list[swap] < list[left_child + 1] {
swap = left_child + 1;
}
if swap == root {
break;
} else {
list.swap(root, swap);
root = swap;
}
}
}
}
impl<T: Sortable> Sort<T> for Heap {
fn sort(&self, list: &[T]) -> Vec<T> {
let mut sorted: Vec<T> = list.iter().cloned().collect();
if sorted.len() <= 1 {
return sorted;
}
self.heapify(&mut sorted);
for i in (1..sorted.len()).rev() {
sorted.swap(i, 0);
self.sift_down(&mut sorted, 0, i - 1);
}
return sorted;
}
}