Here's how I created my binary heap:
int *heapArray; // pointer to array of elements in heap
int capacity = 0; // maximum possible size of min heap
int heap_size; // Current number of elements in min heap
int d = 2;
int parent(int i)
{
return (i/d);
}
void swap(double *x, double *y)
{
double temp = *x;
*x = *y;
*y = temp;
}
double returnHeapValue(int key)
{
return heapArray[key];
}
void initialize(int cap)
{
heap_size = 0;
capacity = cap;
heapArray = (double*)malloc(cap*sizeof(double));
}
void insertJob(double x)
{
if(capacity < 10)
{
capacity = 10;
heapArray = (double*)realloc(heapArray,capacity*sizeof(double));
}
if(heap_size == capacity/2)
{
capacity += 10;
heapArray = (double*)realloc(heapArray,capacity*sizeof(double));
}
heap_size = heap_size + 1;
heapArray[heap_size] = x;
maxHeapSwim(heap_size);
}
void maxHeapSwim(int k)
{
while(k > 1 && heapArray[parent(k)] < heapArray[k] && k!=1)
{
swap(&heapArray[k],&heapArray[parent(k)]);
k = parent(k);
}
}
This is what I did in the main method to insert a bunch of doubles and then print them out:
int main()
{
// test
initialize(20);
insertJob(2.0);
insertJob(3.0);
insertJob(1.0);
insertJob(6.0);
insertJob(4.0);
insertJob(14.0);
insertJob(7.0);
insertJob(9.0);
insertJob(8.0);
insertJob(11.0);
printf("\n");
printf("%f", returnHeapValue(1));
printf("\n");
printf("%f", returnHeapValue(2));
printf("\n");
printf("%f", returnHeapValue(3));
printf("\n");
printf("%f", returnHeapValue(4));
printf("\n");
printf("%f", returnHeapValue(5));
printf("\n");
printf("%f", returnHeapValue(6));
printf("\n");
printf("%f", returnHeapValue(7));
printf("\n");
printf("%f", returnHeapValue(8));
printf("\n");
printf("%f", returnHeapValue(9));
printf("\n");
printf("%f", returnHeapValue(10));
printf("\n");
return 0;
}
However, this is what the output looks like:
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
Why aren't the numbers being printer properly? Is there something I'm doing wrong? When I test it out with Integer values, then everything works fine. But it's not working when I try to insert values of the "double" data type.
EDIT:
I also tried changing the type of heapArray from int to double like this:
double *heapArray;
Unfortunately, that lead to an error in another function that I created:
double delMaxPriorityJob() //This function deletes the largest value (in the root)
{
double max = heapArray[1];
swap(&heapArray[1],&heapArray[heap_size]);
heap_size = heap_size - 1;
maxHeapSink(1);
heapArray[heap_size + 1] = NULL; //The error is in this line
return max;
}
The error says:
"Incompatible types when assigning to type 'double' from type 'void *'"