int main() { int n, j; scanf("%d",&n); heap *test_heap=createHeap(n); for(j=0; j<n; j++) scanf("%d",(test_heap->arr)+j); //builds max heap of the array and sets heapsize to len-1 buildmaxheap(test_heap); // heapsort(test_heap); /*printf("\n%d",HeapExtractMax(test_heap)); printf("\n%d",HeapExtractMax(test_heap)); printf("\n%d",HeapExtractMax(test_heap)); printf("\n%d",HeapExtractMax(test_heap));*/ printHeap(test_heap); printf("\nIncrease key"); HeapIncreaseKey(test_heap,4,18); printHeap(test_heap); printf("\nInsert key"); MaxHeapInsert(test_heap,20); printHeap(test_heap); MaxHeapInsert(test_heap,-5); printHeap(test_heap); MaxHeapInsert(test_heap,10); printHeap(test_heap); printf("\n"); free(test_heap->arr); free(test_heap); return 0; }
void MaxHeapInsert(Heap* heap, int key) { heap->size = heap->size + 1; heap->element[heap->size] = key - 1; HeapIncreaseKey(heap, heap->size, key); }
int HeapDeleteIndex(Heap* ph, int index) { if(index >= ph->size || index < 0) return -1; ph->shif(ph->array[index],-1); ph->array[index]=ph->array[ph->size-1]; ph->shif(ph->array[ph->size-1], index); ph->size--; HeapDecreaseKey(ph,index); HeapIncreaseKey(ph,index); HeapOdfouk(ph); return 1; }
void* HeapPop(Heap* ph) { if(ph->size==0) return NULL; ph->shif(ph->array[0],-1); void* item = ph->array[0]; ph->size--; if(ph->size>0) { ph->array[0]=ph->array[ph->size]; ph->shif(ph->array[ph->size], 0); HeapIncreaseKey(ph,0); } HeapOdfouk(ph); return item; }
void MaxHeapInsert(heap *A, int key) { if(A->heapsize+1==A->len) { int newlen = A->len+1, j; int * newarr = (int*)malloc(newlen*sizeof(int)); for(j=0; j<=A->heapsize; j++) newarr[j]=A->arr[j]; A->len++; A->heapsize++; free(A->arr); A->arr=newarr; } else A->heapsize++; A->arr[A->heapsize]=MIN_VAL; HeapIncreaseKey(A,A->heapsize,key); }