I tried to make several functions which passes a heap as a parameter through the code below. However, it did not turned out to be what I expected it to be.
#include<stdio.h>
void upHeap_min2 (int *heap, int index)
{
if (index == 0)
return;
int parentIdx = getParentIdx(index);
if (heap[index] < heap[parentIdx])
{
int temp = heap[index];
heap[index] = heap[parentIdx];
heap[parentIdx] = temp;
upHeap_min2(heap, parentIdx);
}
}
void pushValue (int *heap, int count, int value)
{
count++;
heap[count] = value;
upHeap_min2(heap, count);
}
void view(int *heap, int count)
{
printf("Values inside heap: ");
for (int i = 0; i < count; i++)
{
printf("%d ", heap[i]);
}
printf("\n");
}
int main()
{
int heapDemo[101];
int count = -1;
pushValue(heapDemo, count, 30);
pushValue(heapDemo, count, 20);
pushValue(heapDemo, count, 40);
pushValue(heapDemo, count, 90);
pushValue(heapDemo, count, 10);
view(heapDemo, count);
return 0;
}
Function to get parent index:
int getParentIdx (int index)
{
return (index-1)/2;
}
The code above should have printed
10 20 40 90 30
But instead it printed nothing. I have also thought to pass it as a double pointer as well but i did not work. Does this mean I cannot pass a heap as a parameter (which means i have to declare the heap as a global variable) or there is another way to do this?