@@ -43,8 +43,7 @@ impl<T: Default + PartialOrd> PriorityQueue<T> {
43
43
} else if self . len ( ) == 1 {
44
44
self . queue . remove ( 1 )
45
45
} else {
46
- let end = self . len ( ) - 1 ;
47
- self . queue . swap ( 1 , end) ;
46
+ self . queue . swap ( 1 , self . len ( ) ) ;
48
47
let v = self . queue . pop_back ( ) ;
49
48
self . heapify_down ( 1 ) ;
50
49
v
@@ -57,24 +56,36 @@ impl<T: Default + PartialOrd> PriorityQueue<T> {
57
56
self . heapify_up ( i) ;
58
57
}
59
58
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
65
81
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] ;
70
83
// 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
+ }
78
89
}
79
90
}
80
91
@@ -95,17 +106,25 @@ mod tests {
95
106
use super :: * ;
96
107
97
108
#[ test]
98
- fn push_works ( ) {
109
+ fn pq_works ( ) {
99
110
let mut pq = PriorityQueue :: new ( ) ;
100
111
assert_eq ! ( None , pq. peak( ) ) ;
112
+ assert_eq ! ( None , pq. pop( ) ) ;
101
113
pq. push ( 50 ) ;
102
114
assert_eq ! ( Some ( & 50 ) , pq. peak( ) ) ;
103
115
pq. push ( 75 ) ;
104
116
pq. push ( 100 ) ;
105
- assert_eq ! ( Some ( & 50 ) , pq. peak( ) ) ;
106
117
dbg ! ( & pq) ;
118
+ assert_eq ! ( Some ( & 50 ) , pq. peak( ) ) ;
107
119
pq. push ( 30 ) ;
108
120
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( ) ) ;
109
128
}
110
129
111
130
}
0 commit comments