// 주함수 void main() { element e1={10}, e2={5}, e3={30}; element e4, e5, e6; HeapType heap; // 히프 생성 init(&heap); // 초기화 // 삽입 insert_max_heap(&heap, e1); insert_max_heap(&heap, e2); insert_max_heap(&heap, e3); // print_heap(&heap); // 삭제 e4 = delete_max_heap(&heap); printf("< %d > ", e4.key); e5 = delete_max_heap(&heap); printf("< %d > ", e5.key); e6 = delete_max_heap(&heap); printf("< %d > \n", e6.key); heap_sort(test,5); }
// 우선 순위 큐인 히프를 이용한 정렬 void heap_sort(element a[], int n) { int i; HeapType h; init(&h); for(i=0;i<n;i++){ insert_max_heap(&h, a[i]); } for(i=(n-1);i>=0;i--){ a[i] = delete_max_heap(&h); } }
int main(void) { // create a max heap first for (int j = 1; j < 11; j++) { element temp; temp.key = j; insert_max_heap(temp, &n); } traverse(); element origin = {3}; element newp = {33}; change_priority(origin, newp, &n); traverse(); return 0; }
void change_priority(element origin, element newp, int *n) { /* origin: the assumed element to be in the heap; newp: new key to replace origin if origin in heap, otherwise add it in; n: the number of elements of the heap. */ int parent, child; int index = inheap(origin, *n); parent = index; child = parent * 2; if (!index) { printf("Origin not in the heap, inserting...\n"); insert_max_heap(origin, n); } else { if (newp.key > heap[index/2].key) { while ((newp.key > heap[index/2].key) && (index != 1)) { heap[index] = heap[index/2]; index /= 2; } heap[index] = newp; } else { while (child <= *n) { if ((child < *n) && (heap[child].key < heap[child+1].key)) child++; if (newp.key >= heap[child].key) break; heap[parent] = heap[child]; child *= 2; } heap[parent] = newp; } } }