int main(int argc, char *argv[]) { // Check arguments if (argc < 2) { printf("Wrong arguments\n"); return EXIT_FAILURE; } int maxnum = atoi(argv[1]); char *filename = argv[2]; // Create new heap heap *theHeap = newHeap(maxnum); // Read lines of file FILE *fp = fopen(filename, "rt"); while(!feof(fp)) { char buffer[256]; fgets(buffer, 256, fp); if (feof(fp)) break; int value = atoi(buffer); insertHeap(theHeap, value); if (isFullHeap(theHeap)) { removeHeap(theHeap); } } // Show contents while(!isEmptyHeap(theHeap)) { int value = removeHeap(theHeap); printf("%d\n", value); } // Delete heap deleteHeap(theHeap); return EXIT_SUCCESS; }
/* Insert number into heap Unspecified behavior if heap is full before insert */ void insertHeap(heap *aHeap, int value) { assert(aHeap != NULL); assert(aHeap->size < aHeap->maxSize); int removeHeap(heap *aHeap); if(isFullHeap(aHeap)) removeHeap(aHeap); //If the heap is full, remove an element int index = aHeap->size; aHeap->array[index] = value; int ins_value = aHeap->array[index]; int par_index = parent(index); //Keep swapping with parent until conditions are satisfied while(index > 0 && aHeap->array[par_index] < ins_value){ aHeap->array[index] = aHeap->array[par_index]; index = par_index; par_index = parent(par_index); } aHeap->array[index] = ins_value; aHeap->size++; //Increment size }