@@ -101,28 +101,22 @@ void binaryHeapDown(void **arr, int currentIndex, int length, int (*cmp)(const v
101
101
if (currentIndex >= length )
102
102
return ;
103
103
104
- int fChildIndex = binaryHeapGetFChildIndex (currentIndex );
105
- int sChildIndex = binaryHeapGetSChildIndex (currentIndex );
104
+ int fChildIndex = binaryHeapGetFChildIndex (currentIndex ),
105
+ sChildIndex = binaryHeapGetSChildIndex (currentIndex ),
106
+ targetChildIndex = -1 ;
106
107
107
- fChildIndex = fChildIndex >= length ? currentIndex : fChildIndex ;
108
- sChildIndex = sChildIndex >= length ? currentIndex : sChildIndex ;
108
+ if (fChildIndex < length || sChildIndex < length ) {
109
109
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 ;
111
114
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
+ }
125
116
117
+ if (targetChildIndex != -1 && cmp (arr [targetChildIndex ], arr [currentIndex ]) > 0 ) {
118
+ binaryHeapSwap (arr , currentIndex , targetChildIndex );
119
+ binaryHeapDown (arr , targetChildIndex , length , cmp );
126
120
}
127
121
128
122
}
0 commit comments