use super::PriorityQueue;
pub struct BinaryHeap<T: PartialOrd> {
heap: Vec<T>,
}
impl<T: PartialOrd> PriorityQueue<T> for BinaryHeap<T> {
fn with_capacity(sz: usize) -> Self {
Self {
heap: Vec::with_capacity(sz),
}
}
fn insert(&mut self, el: T) {
self.heap.push(el);
self.swim(self.heap.len() - 1);
}
fn contains(&self, el: &T) -> bool {
self.heap.contains(el)
}
fn remove(&mut self, el: &T) {
if let Some(idx) = self.heap.iter().position(|x| x == el) {
self.remove_at(idx);
}
}
fn poll(&mut self) -> Option<T> {
self.remove_at(0)
}
}
impl<T: PartialOrd> BinaryHeap<T> {
pub fn swap(&mut self, i: usize, j: usize) {
self.heap.swap(i, j);
}
fn remove_at(&mut self, i: usize) -> Option<T> {
let end = self.heap.len() - 1;
self.heap.swap(i, end);
let removed = self.heap.pop();
let i_ = self.sink(i);
if i_ == i {
self.swim(i);
}
removed
}
fn swim(&mut self, mut k: usize) -> usize {
let mut parent = (k.saturating_sub(1)) / 2;
while k > 0 && self.heap[k] < self.heap[parent] {
self.heap.swap(parent, k);
k = parent;
parent = (k.saturating_sub(1)) / 2;
}
k
}
fn sink(&mut self, mut k: usize) -> usize {
let heap_size = self.heap.len();
loop {
let left = 2 * k + 1; let right = 2 * k + 2;
let smallest = if right < heap_size && self.heap[right] < self.heap[left] {
right
} else {
left
};
if left >= heap_size || self.heap[k] < self.heap[smallest] {
break;
}
self.heap.swap(smallest, k);
k = smallest;
}
k
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_priority_queue_binary_heap() {
let mut pq = BinaryHeap::with_capacity(8);
pq.insert(5);
pq.insert(7);
pq.insert(3);
pq.insert(8);
pq.insert(2);
pq.insert(1);
assert_eq!(pq.poll().unwrap(), 1);
pq.remove(&2);
assert_eq!(pq.poll().unwrap(), 3);
}
}