voidsiftDown(MaxHeap* heap, int parentIdx) { int size = heap->size; while (true) { int leftChild = parentIdx * 2 + 1; int rightChild = parentIdx * 2 + 2; int largest = parentIdx;
if (leftChild < size && heap->data[leftChild] > heap->data[largest]) { largest = leftChild; } if (rightChild < size && heap->data[rightChild] > heap->data[largest]) { largest = rightChild; } if (largest != parentIdx) { swap(&heap->data[largest], &heap->data[parentIdx]); parentIdx = largest; } else { break; } } }
6. 入堆操作(push)
1 2 3 4 5 6 7 8 9 10 11 12
boolpush(MaxHeap* heap, int val) { // 满堆的处理 if (heap->size == heap->capacity) returnfalse;
voiddeleteElement(MaxHeap* heap, int i) { if (i < 0 || i >= heap->size) return; if (i == 0) { pop(heap); return; } if (i == heap->size - 1) { heap->size--; return; } int lastVal = heap->data[heap->size - 1]; heap->size--; int oldVal = heap->data[i]; heap->data[i] = lastVal;