//假設小堆 typedef int HDataType; typedef struct heap { HDataType* _data; int _size; int _capacity; }heap; void Swap(int* a, int* b) { int tmp = a; a = b; b = tmp; } void heapInit(heap* hp) { if (hp == NULL) return; //空堆 hp->_data = NULL; hp->_size = hp->_capacity = 0; } void heapPush(heap* hp, HDataType val) { checkCapacity(hp); //尾插 hp->_data[hp->_size++] = val; //向上調整 shiftUp(hp->_data, hp->_size, hp->_size - 1); } void hpeaPop(heap* hp) { if (hp->_size > 0) { //交換 Swap(&hp->_data[0], &hp->_data[hp->_size - 1]); hp->_size--; //從堆頂位置向下調整 shiftDown(hp->_data, hp->_size, 0); } } HDataType heapTop(heap* hp) { return hp->_data[0]; } int heapEmpty(heap* hp) { if (hp == NULL || hp->_size == 0) return 1; else return 0; } void checkCapacity(heap* hp) { if (hp->_size = hp->_capacity) { int newC = hp->_capacity == 0 ? 1 : 2 * hp->_capacity; hp->_data = (HDataType*)relloc(hp->_data, sizeof(HDataType)*newC); hp->_capacity = newC; } } /* //向下調整 #include<stdio.h> void shiftDown(int* arr, int n, int cur) { //找到孩子的位置 //左孩子 int child = 2 * cur + 1; while (child < n) { //從左孩子找最小的 if (child + 1 < n&&arr[child] > arr[child + 1]) ++child; //和當前數據作比較 //1.孩子小於當前 調整 if (arr[child] < arr[cur]) { int tmp = arr[child]; arr[child] = arr[cur]; arr[cur] = tmp; //更新位置,繼續調整 cur = child; child = 2 * cur + 1; } else //2.孩子>=當前 不調整 break; } } void test() { int arr[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); //建堆:從最後一個非葉子節點開始,向下調整 for (int i = (n - 2) / 2; i >= 0; i--) { shiftDown(arr, n, i); } } //void test() //{ // int arr[] = { 10, 5, 3, 8, 7, 6 }; // shiftDown(arr, sizeof(arr) / sizeof(arr[0]), 0); //} int main() { test(); return 0; }*/