int main(int argc, char *argv[]) { int input; bool isMaxHeap = true, isMinHeap = false; std::printf("Test MaxHeap\n"); Heap <int> MaxHeap(50, isMaxHeap); for (int i = 0; i < 30; i++) { MaxHeap.Push(i*2+3); } std::printf("Top = %d\n", MaxHeap.Top()); for (int i = 0; i < 5; i++) { MaxHeap.Pop(); std::printf("Top = %d\n", MaxHeap.Top()); } std::putchar(10); std::printf("Test MinHeap\n"); Heap <int> MinHeap(50, isMinHeap); for (int i = 0; i < 30; i++) { MinHeap.Push(i*2+3); } std::printf("Top = %d\n", MinHeap.Top()); for (int i = 0; i < 5; i++) { MinHeap.Pop(); std::printf("Top = %d\n", MinHeap.Top()); } return 0; }
int Merge (int arrays[][4], int k, int n, int result[]) { int i=0, j=0, r=0; HeapNode *node = NULL, *minnode = NULL; Heap *h = NULL; init_heap (&h, k); for (i=0; i<k; i++) { node = newnode(); node->data = arrays[i][0]; node->array = i; node->index = 1; HeapAdd (h, node, i); } MinHeap (h); r = 0; for (i=0; i<n*k; i++) { minnode = getMin (h); result[r++] = minnode->data; if (minnode->index < n) { minnode->data = arrays[minnode->array][minnode->index]; minnode->index++; } else { minnode->data = MAX; } MinHeapify (h, 0); } return 0; }
int GetEdge( int CurrentSize ) { /* 给定当前堆的大小CurrentSize,将当前最小边位置弹出并调整堆 */ struct EdgeType temp; /* 将最小边与当前堆的最后一个位置的边交换 */ temp = ESet[0]; ESet[0] = ESet[CurrentSize-1]; ESet[CurrentSize-1] = temp; /* 将剩下的边继续调整成最小堆 */ MinHeap(0, CurrentSize-1); return CurrentSize-1; /* 返回最小边所在位置 */ }
/* Creates the Huffman tree reusing the given HuffmanNodes. nodes: an array of HuffmanNode* length: the length of nodes array returns: the pointer to the root of the huffman tree */ HuffmanNode *genHuffmanTree(HuffmanNode **nodes, int length) { MinHeap min = MinHeap(nodes, length);//create the array with minHeap constructor while (min.heapSize > 1)//it will run until the array has size one { HuffmanNode *L, *R;//we make the nodes for left and right L = min.extractMin();//we extract the min from the heap and assign it to left R = min.extractMin();//we do the same for the right HuffmanNode *internal = new HuffmanNode(L->frequency + R->frequency, L, R);//we create an internal node with the sum of the frequency left and right. //we also assign left and right to be child of internal min.insert(internal);//we insert the internal node back into the heap } return min.extractMin();//we extract the min but since we only got one element left in the array, this should be the root. }
void klargest (int arr[], int n, int k) { if (n <= 0 || k <= 0 || n < k ) return; int i = 0, min = 0; Heap *h = NULL; init_heap (&h, k); for (i=0; i<k; i++) { AddHeap (h, arr[i], i); } MinHeap (h); for (; i<n; i++) { Heapmin (h, &min); if (arr[i] > min) { ReplaceMin (h, arr[i]); MinHeapify (h, 0); } } printHeap (h); return; }
void InitializeESet ( int M ) { /* 初始化最小堆 */ int i; for (i=M/2; i>=0; i--) MinHeap(i, M); }