Skip to content

Commit 4612757

Browse files
committed
skew heap non-recursive merge
1 parent 25a2f7b commit 4612757

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

skew-heap/src/skewheap.rs

+39-9
Original file line numberDiff line numberDiff line change
@@ -13,45 +13,70 @@ impl<T: Ord> SkewHeap<T> {
1313
self.root.is_none()
1414
}
1515

16-
pub fn push(&mut self, x: T) {
17-
self.root = Node::merge(self.root.take(), Node::singleton(x));
16+
pub fn push(&mut self, value: T) {
17+
self.root = Node::merge(self.root.take(), Node::singleton(value));
1818
}
1919

2020
pub fn pop_min(&mut self) -> Option<T> {
2121
let root = self.root.take()?;
22-
let x = root.x;
22+
let x = root.value;
2323
self.root = Node::merge(root.l, root.r);
2424
Some(x)
2525
}
2626
}
2727

2828
pub struct Node<T: Ord> {
29-
x: T,
29+
value: T,
3030
l: Option<Box<Node<T>>>,
3131
r: Option<Box<Node<T>>>,
3232
}
3333

3434
impl<T: Ord> Node<T> {
35-
pub fn singleton(x: T) -> Option<Box<Node<T>>> {
35+
pub fn singleton(value: T) -> Option<Box<Node<T>>> {
3636
Some(Box::new(Node {
37-
x,
37+
value,
3838
l: None,
3939
r: None,
4040
}))
4141
}
4242

43+
/*
4344
pub fn merge(a: Option<Box<Node<T>>>, b: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {
4445
match (a, b) {
4546
(None, b) => b,
4647
(a, None) => a,
4748
(Some(a), Some(b)) => {
48-
let (mut a, b) = if a.x < b.x { (a, b) } else { (b, a) };
49+
let (mut a, b) = if a.value < b.value { (a, b) } else { (b, a) };
4950
a.r = Self::merge(a.r, Some(b));
5051
swap(&mut a.l, &mut a.r);
5152
Some(a)
5253
}
5354
}
5455
}
56+
*/
57+
58+
pub fn merge(mut a: Option<Box<Node<T>>>, mut b: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {
59+
let mut stack = Vec::new();
60+
let mut ret = loop {
61+
match (a, b) {
62+
(None, b) => break b,
63+
(a, None) => break a,
64+
(Some(x), Some(y)) => {
65+
let (mut x, y) = if x.value < y.value { (x, y) } else { (y, x) };
66+
let r = x.r.take();
67+
stack.push(x);
68+
a = r;
69+
b = Some(y);
70+
}
71+
}
72+
};
73+
while let Some(mut x) = stack.pop() {
74+
x.r = ret;
75+
swap(&mut x.l, &mut x.r);
76+
ret = Some(x);
77+
}
78+
ret
79+
}
5580
}
5681

5782
#[cfg(test)]
@@ -61,7 +86,9 @@ mod tests {
6186
#[test]
6287
fn test_skew_heap() {
6388
let mut heap = SkewHeap::new();
64-
for x in [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9, 9, 9] {
89+
for x in [
90+
1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9, 9, 9,
91+
] {
6592
heap.push(x);
6693
}
6794
let mut v = Vec::new();
@@ -72,6 +99,9 @@ mod tests {
7299
};
73100
v.push(x);
74101
}
75-
assert_eq!(v, vec![1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9, 9, 9]);
102+
assert_eq!(
103+
v,
104+
vec![1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9, 9, 9]
105+
);
76106
}
77107
}

0 commit comments

Comments
 (0)