Bug fixes

This commit is contained in:
hal8174 2024-08-27 13:53:31 +02:00
parent be1d26ebd0
commit a11b39cf9f
8 changed files with 336 additions and 70 deletions

View file

@ -1,3 +1,4 @@
use std::fmt::Debug;
pub mod fibonacci_heap;
pub trait PriorityQueue<Item>
@ -17,7 +18,8 @@ where
#[derive(Debug)]
pub struct BinaryHeap<Item> {
data: Vec<Item>,
nextfree: usize,
data: Vec<(usize, Item)>,
}
impl<Item> BinaryHeap<Item>
@ -47,16 +49,16 @@ where
fn upheap(&mut self, index: usize) {
if index > 0 {
let parent = (index - 1) / 2;
if self.data[parent] > self.data[index] {
if self.data[parent].1 > self.data[index].1 {
self.data.swap(parent, index);
self.upheap(parent);
}
}
}
fn search(&self, item: &Item) -> Option<usize> {
fn search(&self, id: usize) -> Option<usize> {
for (i, d) in self.data.iter().enumerate() {
if d == item {
if d.0 == id {
return Some(i);
}
}
@ -68,12 +70,13 @@ impl<Item> PriorityQueue<Item> for BinaryHeap<Item>
where
Item: PartialOrd + Clone,
{
type Handle = Item;
type Handle = usize;
fn insert(&mut self, item: Item) -> Self::Handle {
self.data.push(item.clone());
self.data.push((self.nextfree, item.clone()));
self.upheap(self.data.len() - 1);
item
self.nextfree += 1;
self.nextfree - 1
}
fn pop_min(&mut self) -> Option<Item> {
@ -82,19 +85,59 @@ where
} else {
let d = self.data.swap_remove(0);
self.downheap(0);
Some(d)
Some(d.1)
}
}
fn decrease_key(&mut self, handle: &Self::Handle, f: impl Fn(&mut Item)) {
if let Some(index) = self.search(handle) {
f(&mut self.data[index]);
if let Some(index) = self.search(*handle) {
f(&mut self.data[index].1);
self.upheap(index);
}
}
fn new() -> Self {
Self { data: Vec::new() }
Self {
data: Vec::new(),
nextfree: 0,
}
}
}
#[derive(Debug)]
pub struct Trace<P> {
inner: P,
}
impl<P, I> PriorityQueue<I> for Trace<P>
where
I: PartialOrd + Clone + Debug,
P: PriorityQueue<I>,
{
type Handle = P::Handle;
fn new() -> Self {
println!("New priority queue.");
Self { inner: P::new() }
}
fn insert(&mut self, item: I) -> Self::Handle {
println!("Insert: {item:?}");
self.inner.insert(item)
}
fn pop_min(&mut self) -> Option<I> {
let min = self.inner.pop_min();
println!("Pop min: {min:?}");
min
}
fn decrease_key(&mut self, handle: &Self::Handle, f: impl Fn(&mut I)) {
self.inner.decrease_key(handle, |i| {
let old_i = i.clone();
f(i);
println!("Decrease key: {old_i:?} -> {i:?}");
})
}
}