I created a binary heap using C. Here are the functions to initialize the heap and insert the values
int *heapArray; // pointer to array of elements in heap
int capacity = 0; // maximum possible size of min heap, initially set to 0
int heap_size; // Current number of elements in min heap
int d = 2; //max number of children per node
int getParent(int i) //get the parent index of i
{
return (i/d);
}
bool isFull() //check if heap is full
{
if(heap_size == capacity)
return true;
if(heap_size < capacity)
return false;
}
void initializeHeap(int cap) //initialize the heap
{
heap_size = 0;
capacity = cap;
heapArray = (int*)malloc(cap*sizeof(int));
}
void insertValue(int x) //insert a value into the heap
{
if(isFull()) //If heap is already full, double the heap size
{
capacity = 2*capacity;
heapArray = realloc(heapArray,capacity*sizeof(int));
}
heap_size = heap_size + 1;
heapArray[heap_size] = x; //insert new value into heap (not zero-indexed)
maxHeapSwim(heap_size);
}
void maxHeapSwim(int k) //move value up the heap to maintain max-heap order
{
while(k > 1 && heapArray[getParent(k)] < heapArray[k])
{
swap(&heapArray[k],&heapArray[parent(k)]);
k = parent(k);
}
}
Then in the main() method, I tried to insert values into the heap and print out the values:
int main()
{
initializeHeap(1); //Set the heap capacity to 1
insertValue(2);
insertValue(3);
insertValue(1);
insertValue(6);
insertValue(4);
printf("\n");
printf("%i", heapArray[1]);
printf("\n");
printf("%i", heapArray[2]);
printf("\n");
printf("%i", heapArray[3]);
printf("\n");
printf("%i", heapArray[4]);
printf("\n");
printf("%i", heapArray[5]);
printf("\n");
return 0;
}
Since this is a max-heap, I was hoping the output would look like this:
6
4
1
2
3
But instead, it looked like this:
6
4
1
0
3
I don't understand. Why is the 2 turning into a 0? I have a feeling it has something to do with how I'm doubling the heap size in the insertValue() function....maybe the way I'm using realloc. Is there something I'm doing incorrectly?
Another thing to note is that my binary heap isn't zero-indexed. The first value is inserted into heapArray[1], the second value into heapArray[2], and so on.