// 下滤算法 void filter(int *data, unsigned int i, unsigned int n) { int currentNodeValue = data[i]; unsigned int child = leftChildIndex(i); while (child < n) { if (hasSibling(child, n) && data[child + 1] < data[child]) { child++; // 取左右子节点中,更小的值 } if (data[child] < currentNodeValue) { data[i] = data[child]; i = child; child = leftChildIndex(i); } else { break; } } data[i] = currentNodeValue; }
void MinHeapify(MinHeap *A, long int index) { long int currentIndex = index, minIndex, temp, left, right; while(1) { minIndex = currentIndex; left = leftChildIndex(currentIndex); right = rightChildIndex(currentIndex); /* Find the index of the minimum element */ if(left <= A->heapSize && A->arr[left] < A->arr[minIndex]) minIndex = left; if(right <= A->heapSize && A->arr[right] < A->arr[minIndex]) minIndex = right; if(minIndex != currentIndex) { /* Swap the two elements */ temp = A->arr[minIndex]; A->arr[minIndex] = A->arr[currentIndex]; A->arr[currentIndex] = temp; currentIndex = minIndex; } else break; } }
static void shiftdown(MCHeap* heap, size_t index) { size_t i = index, l, r; while (1) { l = leftChildIndex(i); r = rightChildIndex(i); if (MCGenericCompare(heap->values[i], heap->values[l]) > 0) { swapNode(heap, i, l); i = l; } else if (MCGenericCompare(heap->values[i], heap->values[r]) > 0) { swapNode(heap, i, r); i = r; }else{ break; } } }