File tree Expand file tree Collapse file tree 1 file changed +11
-8
lines changed Expand file tree Collapse file tree 1 file changed +11
-8
lines changed Original file line number Diff line number Diff line change @@ -188,22 +188,25 @@ where
188188 // This binary heap respects the invariant `parent >= child`.
189189 let mut sift_down = |v : & mut [ T ] , mut node| {
190190 loop {
191- // Children of `node`:
192- let left = 2 * node + 1 ;
193- let right = 2 * node + 2 ;
191+ // Children of `node`.
192+ let mut child = 2 * node + 1 ;
193+ if child >= v. len ( ) {
194+ break ;
195+ }
194196
195197 // Choose the greater child.
196- let greater =
197- if right < v. len ( ) && is_less ( & v[ left] , & v[ right] ) { right } else { left } ;
198+ if child + 1 < v. len ( ) && is_less ( & v[ child] , & v[ child + 1 ] ) {
199+ child += 1 ;
200+ }
198201
199202 // Stop if the invariant holds at `node`.
200- if greater >= v . len ( ) || !is_less ( & v[ node] , & v[ greater ] ) {
203+ if !is_less ( & v[ node] , & v[ child ] ) {
201204 break ;
202205 }
203206
204207 // Swap `node` with the greater child, move one step down, and continue sifting.
205- v. swap ( node, greater ) ;
206- node = greater ;
208+ v. swap ( node, child ) ;
209+ node = child ;
207210 }
208211 } ;
209212
You can’t perform that action at this time.
0 commit comments