@@ -101,28 +101,22 @@ void binaryHeapDown(void **arr, int currentIndex, int length, int (*cmp)(const v
101101 if (currentIndex >= length )
102102 return ;
103103
104- int fChildIndex = binaryHeapGetFChildIndex (currentIndex );
105- int sChildIndex = binaryHeapGetSChildIndex (currentIndex );
104+ int fChildIndex = binaryHeapGetFChildIndex (currentIndex ),
105+ sChildIndex = binaryHeapGetSChildIndex (currentIndex ),
106+ targetChildIndex = -1 ;
106107
107- fChildIndex = fChildIndex >= length ? currentIndex : fChildIndex ;
108- sChildIndex = sChildIndex >= length ? currentIndex : sChildIndex ;
108+ if (fChildIndex < length || sChildIndex < length ) {
109109
110- if (cmp (arr [currentIndex ], arr [fChildIndex ]) < 0 && cmp (arr [currentIndex ], arr [sChildIndex ]) < 0 ) {
110+ if (fChildIndex < length && sChildIndex < length )
111+ targetChildIndex = cmp (arr [fChildIndex ], arr [sChildIndex ]) > 0 ? fChildIndex : sChildIndex ;
112+ else
113+ targetChildIndex = fChildIndex >= length ? sChildIndex : fChildIndex ;
111114
112- int biggestChildIndex = cmp (arr [fChildIndex ], arr [sChildIndex ]) < 0 ? sChildIndex : fChildIndex ;
113- binaryHeapSwap (arr , currentIndex , biggestChildIndex );
114- binaryHeapDown (arr , biggestChildIndex , length , cmp );
115-
116- } else if (cmp (arr [currentIndex ], arr [fChildIndex ]) < 0 ) {
117-
118- binaryHeapSwap (arr , currentIndex , fChildIndex );
119- binaryHeapDown (arr , fChildIndex , length , cmp );
120-
121- } else if (cmp (arr [currentIndex ], arr [sChildIndex ]) < 0 ) {
122-
123- binaryHeapSwap (arr , currentIndex , sChildIndex );
124- binaryHeapDown (arr , sChildIndex , length , cmp );
115+ }
125116
117+ if (targetChildIndex != -1 && cmp (arr [targetChildIndex ], arr [currentIndex ]) > 0 ) {
118+ binaryHeapSwap (arr , currentIndex , targetChildIndex );
119+ binaryHeapDown (arr , targetChildIndex , length , cmp );
126120 }
127121
128122}
0 commit comments