Skip to content

Commit e08d2c5

Browse files
committed
PQ: Finished priority queue
1 parent c60a589 commit e08d2c5

File tree

1 file changed

+39
-20
lines changed

1 file changed

+39
-20
lines changed

src/priority_queue.rs

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ impl<T: Default + PartialOrd> PriorityQueue<T> {
4343
} else if self.len() == 1 {
4444
self.queue.remove(1)
4545
} else {
46-
let end = self.len() - 1;
47-
self.queue.swap(1, end);
46+
self.queue.swap(1, self.len());
4847
let v = self.queue.pop_back();
4948
self.heapify_down(1);
5049
v
@@ -57,24 +56,36 @@ impl<T: Default + PartialOrd> PriorityQueue<T> {
5756
self.heapify_up(i);
5857
}
5958

60-
// child
61-
// l (i * 2)
62-
// r (i * 2) + 1
63-
// parent
64-
// (i/2)
59+
fn left(&self, i: usize) -> (usize, Option<&T>) {
60+
let l_i = i * 2;
61+
(l_i, self.queue.get(l_i))
62+
}
63+
64+
fn right(&self, i: usize) -> (usize, Option<&T>) {
65+
let r_i = (i * 2) + 1;
66+
(r_i, self.queue.get(r_i))
67+
}
68+
69+
fn min_child (&self, i: usize) -> (usize, Option<&T>) {
70+
let (l_i, l) = self.left(i);
71+
let (r_i, r) = self.right(i);
72+
73+
match (l, r) {
74+
(Some(l), Some(r)) if l > r => (r_i, Some(r)),
75+
(Some(l), _) => (l_i, Some(l)),
76+
_ => (0, None),
77+
}
78+
}
79+
80+
/// Panics if i is out of bounds
6581
fn heapify_down(&mut self, i: usize) {
66-
let v = self.queue.get(i);
67-
let l = self.queue.get(i * 2);
68-
let r = self.queue.get((i * 2) + 1);
69-
// find min child
82+
let v = &self.queue[i];
7083
// if min child is < v, swap with min child
71-
match (v, l, r) {
72-
(Some(v), Some(l), _) if l < v => {
73-
},
74-
(Some(v), _, Some(r)) if r < v => {
75-
76-
},
77-
_ => (),
84+
if let (c_i, Some(child)) = self.min_child(i) {
85+
if child < v {
86+
self.queue.swap(c_i, i);
87+
self.heapify_down(c_i);
88+
}
7889
}
7990
}
8091

@@ -95,17 +106,25 @@ mod tests {
95106
use super::*;
96107

97108
#[test]
98-
fn push_works() {
109+
fn pq_works() {
99110
let mut pq = PriorityQueue::new();
100111
assert_eq!(None, pq.peak());
112+
assert_eq!(None, pq.pop());
101113
pq.push(50);
102114
assert_eq!(Some(&50), pq.peak());
103115
pq.push(75);
104116
pq.push(100);
105-
assert_eq!(Some(&50), pq.peak());
106117
dbg!(&pq);
118+
assert_eq!(Some(&50), pq.peak());
107119
pq.push(30);
108120
dbg!(&pq);
121+
assert_eq!(Some(&30), pq.peak());
122+
assert_eq!(Some(30), pq.pop());
123+
dbg!(&pq);
124+
assert_eq!(Some(50), pq.pop());
125+
assert_eq!(Some(75), pq.pop());
126+
assert_eq!(Some(100), pq.pop());
127+
assert_eq!(None, pq.pop());
109128
}
110129

111130
}

0 commit comments

Comments
 (0)