forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.rs
210 lines (183 loc) · 4.73 KB
/
heap.rs
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Heap data structure
// Takes a closure as a comparator to allow for min-heap, max-heap, and works with custom key functions
use std::cmp::Ord;
use std::default::Default;
pub struct Heap<T>
where
T: Default,
{
count: usize,
items: Vec<T>,
comparator: fn(&T, &T) -> bool,
}
impl<T> Heap<T>
where
T: Default,
{
pub fn new(comparator: fn(&T, &T) -> bool) -> Self {
Self {
count: 0,
// Add a default in the first spot to offset indexes
// for the parent/child math to work out.
// Vecs have to have all the same type so using Default
// is a way to add an unused item.
items: vec![T::default()],
comparator,
}
}
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.len() > 0
}
pub fn add(&mut self, value: T) {
self.count += 1;
self.items.push(value);
// Heapify Up
let mut idx = self.count;
while self.parent_idx(idx) > 0 {
let pdx = self.parent_idx(idx);
if (self.comparator)(&self.items[idx], &self.items[pdx]) {
self.items.swap(idx, pdx);
}
idx = pdx;
}
}
fn parent_idx(&self, idx: usize) -> usize {
idx / 2
}
fn children_present(&self, idx: usize) -> bool {
self.left_child_idx(idx) <= self.count
}
fn left_child_idx(&self, idx: usize) -> usize {
idx * 2
}
fn right_child_idx(&self, idx: usize) -> usize {
self.left_child_idx(idx) + 1
}
fn smallest_child_idx(&self, idx: usize) -> usize {
if self.right_child_idx(idx) > self.count {
self.left_child_idx(idx)
} else {
let ldx = self.left_child_idx(idx);
let rdx = self.right_child_idx(idx);
if (self.comparator)(&self.items[ldx], &self.items[rdx]) {
ldx
} else {
rdx
}
}
}
}
impl<T> Heap<T>
where
T: Default + Ord,
{
/// Create a new MinHeap
pub fn new_min() -> Self {
Self::new(|a, b| a < b)
}
/// Create a new MaxHeap
pub fn new_max() -> Self {
Self::new(|a, b| a > b)
}
}
impl<T> Iterator for Heap<T>
where
T: Default,
{
type Item = T;
fn next(&mut self) -> Option<T> {
let next = if self.count == 0 {
None
} else {
// This feels like a function built for heap impl :)
// Removes an item at an index and fills in with the last item
// of the Vec
let next = self.items.swap_remove(1);
Some(next)
};
self.count -= 1;
if self.count > 0 {
// Heapify Down
let mut idx = 1;
while self.children_present(idx) {
let cdx = self.smallest_child_idx(idx);
if !(self.comparator)(&self.items[idx], &self.items[cdx]) {
self.items.swap(idx, cdx);
}
idx = cdx;
}
}
next
}
}
pub struct MinHeap;
impl MinHeap {
pub fn new<T>() -> Heap<T>
where
T: Default + Ord,
{
Heap::new(|a, b| a < b)
}
}
pub struct MaxHeap;
impl MaxHeap {
pub fn new<T>() -> Heap<T>
where
T: Default + Ord,
{
Heap::new(|a, b| a > b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_heap() {
let mut heap = MinHeap::new();
heap.add(4);
heap.add(2);
heap.add(9);
heap.add(11);
assert_eq!(heap.len(), 4);
assert_eq!(heap.next(), Some(2));
assert_eq!(heap.next(), Some(4));
assert_eq!(heap.next(), Some(9));
heap.add(1);
assert_eq!(heap.next(), Some(1));
}
#[test]
fn test_max_heap() {
let mut heap = MaxHeap::new();
heap.add(4);
heap.add(2);
heap.add(9);
heap.add(11);
assert_eq!(heap.len(), 4);
assert_eq!(heap.next(), Some(11));
assert_eq!(heap.next(), Some(9));
assert_eq!(heap.next(), Some(4));
heap.add(1);
assert_eq!(heap.next(), Some(2));
}
struct Point(/* x */ i32, /* y */ i32);
impl Default for Point {
fn default() -> Self {
Self(0, 0)
}
}
#[test]
fn test_key_heap() {
let mut heap: Heap<Point> = Heap::new(|a, b| a.0 < b.0);
heap.add(Point(1, 5));
heap.add(Point(3, 10));
heap.add(Point(-2, 4));
assert_eq!(heap.len(), 3);
assert_eq!(heap.next().unwrap().0, -2);
assert_eq!(heap.next().unwrap().0, 1);
heap.add(Point(50, 34));
assert_eq!(heap.next().unwrap().0, 3);
}
}