rust_dsa/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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/// A [priority queue](http://en.wikipedia.org/wiki/Priority_queue) implementation
/// backed by a [binary heap](https://en.wikipedia.org/wiki/Binary_heap).
///
/// [`BinaryHeap::pop`] removes the *smallest* item.
///
/// # Example
///
/// ```
/// use rust_dsa::BinaryHeap;
///
/// // First, we create a new heap.
/// let mut heap = BinaryHeap::new();
///
/// // Then we can add items in any order.
/// heap.insert(4);
/// heap.insert(1);
/// heap.insert(3);
///
/// // We can peek at the minimum item.
/// assert_eq!(heap.peek(), Some(&1));
///
/// // And pop them off in ascending order.
/// assert_eq!(heap.pop(), Some(1));
/// assert_eq!(heap.pop(), Some(3));
/// assert_eq!(heap.pop(), Some(4));
/// assert_eq!(heap.pop(), None);
///
/// // We can also create heaps from arrays.
/// let mut heap = BinaryHeap::from([2, 6, 2]);
///
/// // And heaps can contain duplicate items.
/// assert_eq!(heap.pop(), Some(2));
/// assert_eq!(heap.pop(), Some(2));
///
/// assert_eq!(heap.len(), 1);
/// ```
///
/// # Runtime complexity
///
/// | Operation | Runtime Complexity |
/// | ---------------------- | ------------------ |
/// | [`BinaryHeap::insert`] | *O*(log *n*) |
/// | [`BinaryHeap::peek`] | *O*(1) |
/// | [`BinaryHeap::pop`] | *O*(log *n*) |
/// | [`BinaryHeap::from`] | *O*(*n*) |
#[derive(Clone)]
pub struct BinaryHeap<T> {
items: Vec<T>,
}
impl<T> BinaryHeap<T> {
/// Creates an empty binary heap.
pub fn new() -> Self {
BinaryHeap { items: Vec::new() }
}
/// Inserts an item into the binary heap.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let mut heap = BinaryHeap::new();
/// heap.insert(4);
/// heap.insert(1);
/// heap.insert(3);
///
/// assert_eq!(heap.len(), 3);
/// assert_eq!(heap.peek(), Some(&1));
/// ```
pub fn insert(&mut self, item: T)
where
T: Ord,
{
self.items.push(item);
self.bubble_up(self.len() - 1);
}
/// Returns the smallest item in the binary heap, or `None` if the heap is empty.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let mut heap = BinaryHeap::from([2, 1]);
/// assert_eq!(heap.peek(), Some(&1));
///
/// heap.clear();
/// assert_eq!(heap.peek(), None);
/// ```
pub fn peek(&self) -> Option<&T> {
self.items.get(0)
}
/// Removes and returns the smallest item in the binary heap, or returns `None`
/// if the heap is empty.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let mut heap = BinaryHeap::from([4, 1, 3]);
///
/// assert_eq!(heap.pop(), Some(1));
/// assert_eq!(heap.pop(), Some(3));
/// assert_eq!(heap.pop(), Some(4));
/// assert_eq!(heap.pop(), None);
/// ```
pub fn pop(&mut self) -> Option<T>
where
T: Ord,
{
if self.is_empty() {
None
} else {
let min = self.items.swap_remove(0);
self.bubble_down(0);
Some(min)
}
}
/// Returns the length of the binary heap.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let mut heap = BinaryHeap::from([1, 2, 3]);
/// assert_eq!(heap.len(), 3);
///
/// heap.clear();
/// assert_eq!(heap.len(), 0);
/// ```
pub fn len(&self) -> usize {
self.items.len()
}
/// Returns `true` if the binary heap is empty.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let mut heap = BinaryHeap::from([1, 2]);
/// assert!(!heap.is_empty());
///
/// heap.clear();
/// assert!(heap.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Clears the binary heap.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let mut heap = BinaryHeap::from([1, 2]);
///
/// heap.clear();
/// assert!(heap.is_empty());
/// ```
pub fn clear(&mut self) {
self.items.clear()
}
/// Repeatedly swaps the node at `index` with its parent until the heap
/// invariant is restored.
fn bubble_up(&mut self, mut index: usize)
where
T: Ord,
{
while index > 0 {
let parent = (index - 1) / 2;
if self.items[parent] > self.items[index] {
self.items.swap(parent, index);
index = parent;
} else {
break;
}
}
}
/// Repeatedly swaps the node at `index` with one of its children until the heap
/// invariant is restored.
fn bubble_down(&mut self, mut index: usize)
where
T: Ord,
{
loop {
// find the index of the smallest child
let child1 = 2 * index + 1;
let child2 = child1 + 1;
let mindex = if child2 >= self.len() || self.items[child1] < self.items[child2] {
child1
} else {
child2
};
// if the item at `index` is greater than its smallest child, swap the two
if mindex < self.len() && self.items[index] > self.items[mindex] {
self.items.swap(index, mindex);
index = mindex;
} else {
break;
}
}
}
}
impl<T> IntoIterator for BinaryHeap<T>
where
T: Ord,
{
type IntoIter = IntoIter<T>;
type Item = T;
/// Creates an iterator that iterates over the heap's items in ascending order.
///
/// # Example
/// ```
/// use rust_dsa::BinaryHeap;
///
/// let heap = BinaryHeap::from([4, 2, 3, 1]);
///
/// for x in heap {
/// // prints 1, 2, 3, 4
/// println!("{x}");
/// }
/// ```
fn into_iter(self) -> IntoIter<T> {
IntoIter { heap: self }
}
}
pub struct IntoIter<T> {
heap: BinaryHeap<T>,
}
impl<T> Iterator for IntoIter<T>
where
T: Ord,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.heap.pop()
}
}
impl<T> FromIterator<T> for BinaryHeap<T>
where
T: Ord,
{
/// Uses the [heapify algorithm](https://johnderinger.wordpress.com/2012/12/28/heapify/)
/// to create a [BinaryHeap] in *O*(*n*) time.
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
let mut heap = BinaryHeap {
items: iter.into_iter().collect(),
};
for i in (0..heap.len()).rev() {
heap.bubble_down(i);
}
heap
}
}
impl<T, const N: usize> From<[T; N]> for BinaryHeap<T>
where
T: Ord,
{
/// Uses the [heapify algorithm](https://johnderinger.wordpress.com/2012/12/28/heapify/)
/// to create a [BinaryHeap] in *O*(*n*) time.
fn from(array: [T; N]) -> BinaryHeap<T>
where
T: Ord,
{
array.into_iter().collect()
}
}
impl<T> Default for BinaryHeap<T> {
fn default() -> BinaryHeap<T> {
BinaryHeap::new()
}
}