Add heapify function to binary heap

This commit is contained in:
Michael Bradley 2025-01-04 23:31:28 +13:00
parent ee3cb08fe6
commit 6bb65f6493
Signed by: MichaelBradley
SSH key fingerprint: SHA256:cj/YZ5VT+QOKncqSkx+ibKTIn0Obg7OIzwzl9BL8EO8
3 changed files with 24 additions and 12 deletions

View file

@ -103,6 +103,18 @@ impl<T: Ord + Copy> BinaryHeap<T> {
}
}
impl<T: Ord + Copy> FromIterator<T> for BinaryHeap<T> {
fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Self {
let mut this = Self {
data: Vec::from_iter(iter),
};
for i in (0..=(this.data.len() / 2)).rev() {
this.sift_down(i);
}
this
}
}
impl<T: Ord + Copy> PureBacking<T> for BinaryHeap<T> {
fn new() -> Self {
Self { data: vec![] }

View file

@ -2,7 +2,7 @@
pub mod binary_heap;
/// A data structure usable for backing a "pure" queue
pub trait PureBacking<T: Ord> {
pub trait PureBacking<T: Ord>: FromIterator<T> {
/// Instantiates a new data structure
fn new() -> Self;
/// Places an item into the queue

View file

@ -3,26 +3,26 @@ mod tests {
use pyority_queue::backing::pure::{binary_heap::BinaryHeap, PureBacking};
#[test]
fn test_pure_binary_heap() {
fn test_pure_binary_heap_manual_creation() {
let mut heap = BinaryHeap::new();
assert_eq!(heap.len(), 0);
heap.add(4);
assert_eq!(heap.len(), 1);
heap.add(-3);
assert_eq!(heap.len(), 2);
heap.add(6);
assert_eq!(heap.len(), 3);
heap.add(1);
assert_eq!(heap.len(), 4);
assert_eq!(heap.pop(), Some(-3));
assert_eq!(heap.len(), 3);
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.len(), 2);
assert_eq!(heap.pop(), Some(4));
assert_eq!(heap.len(), 1);
assert_eq!(heap.pop(), Some(6));
assert_eq!(heap.len(), 0);
assert_eq!(heap.pop(), None);
assert_eq!(heap.len(), 0);
}
#[test]
fn test_pure_binary_heap_from_iter() {
let mut heap = BinaryHeap::from_iter(vec![7, 3, 6, 9]);
assert_eq!(heap.pop(), Some(3));
assert_eq!(heap.pop(), Some(6));
assert_eq!(heap.pop(), Some(7));
assert_eq!(heap.pop(), Some(9));
assert_eq!(heap.pop(), None);
}
}