Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve mergeable_heap.rs #207

Merged
merged 1 commit into from
Sep 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions rust/structures/mergeable_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,22 @@ impl<V: PartialOrd> Heap<V> {
}))
}

fn merge(a: Option<Box<Heap<V>>>, b: Option<Box<Heap<V>>>) -> Option<Box<Heap<V>>> {
fn merge(mut a: Option<Box<Heap<V>>>, mut b: Option<Box<Heap<V>>>) -> Option<Box<Heap<V>>> {
if a.is_none() {
return b;
}
if b.is_none() {
return a;
}
let mut ra = a.unwrap();
let mut rb = b.unwrap();
if ra.value > rb.value {
swap(&mut ra, &mut rb);
if a.as_ref()?.value > b.as_ref()?.value {
swap(&mut a, &mut b);
}
let mut ha = a?;
if rand::random() {
swap(&mut ra.left, &mut ra.right);
swap(&mut ha.left, &mut ha.right);
}
ra.left = Self::merge(ra.left, Some(rb));
Some(ra)
ha.left = Self::merge(ha.left, b);
Some(ha)
}

fn remove_min(heap: Option<Box<Heap<V>>>) -> (Option<Box<Heap<V>>>, V) {
Expand Down
Loading