Bug fixes

This commit is contained in:
hal8174 2024-08-31 02:00:28 +02:00
parent a11b39cf9f
commit f20a1841c9
6 changed files with 75 additions and 25 deletions

View file

@ -19,7 +19,13 @@ where
#[derive(Debug)]
pub struct BinaryHeap<Item> {
nextfree: usize,
data: Vec<(usize, Item)>,
data: Vec<BinaryHeapEntry<Item>>,
}
#[derive(Debug)]
struct BinaryHeapEntry<Item> {
id: usize,
item: Item,
}
impl<Item> BinaryHeap<Item>
@ -31,16 +37,16 @@ where
let right = 2 * index + 2;
if right < self.data.len() {
let smaller = if self.data[left] < self.data[right] {
let smaller = if self.data[left].item < self.data[right].item {
left
} else {
right
};
if self.data[index] > self.data[smaller] {
if self.data[index].item > self.data[smaller].item {
self.data.swap(index, smaller);
self.downheap(smaller);
}
} else if left < self.data.len() && self.data[index] > self.data[left] {
} else if left < self.data.len() && self.data[index].item > self.data[left].item {
self.data.swap(index, left);
self.downheap(left);
}
@ -49,7 +55,7 @@ where
fn upheap(&mut self, index: usize) {
if index > 0 {
let parent = (index - 1) / 2;
if self.data[parent].1 > self.data[index].1 {
if self.data[parent].item > self.data[index].item {
self.data.swap(parent, index);
self.upheap(parent);
}
@ -58,7 +64,7 @@ where
fn search(&self, id: usize) -> Option<usize> {
for (i, d) in self.data.iter().enumerate() {
if d.0 == id {
if d.id == id {
return Some(i);
}
}
@ -73,7 +79,10 @@ where
type Handle = usize;
fn insert(&mut self, item: Item) -> Self::Handle {
self.data.push((self.nextfree, item.clone()));
self.data.push(BinaryHeapEntry {
id: self.nextfree,
item: item.clone(),
});
self.upheap(self.data.len() - 1);
self.nextfree += 1;
self.nextfree - 1
@ -85,13 +94,13 @@ where
} else {
let d = self.data.swap_remove(0);
self.downheap(0);
Some(d.1)
Some(d.item)
}
}
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].1);
f(&mut self.data[index].item);
self.upheap(index);
}
}