I'm trying to get a minHeap from an array, but I can't get it right The input I've tried is: 4 3 2 1 The output I got is: 2 3 4 1
First I tried with using only an array of int for storing the heap and it worked, then I changed and used an array of struct node, but the final heap isn't a minHeap
Here is the main code:
int main(){
makeMinHeap(v,vSize-1); // v is the pointer to the array of struct node, and vSize is the
// size of the array
}
void makeMinHeap(struct node *h, int size) {
for (int i = floor(size/2); i >= 0 ; i--) {
heapify(h, i,size);
}
}
void heapify(struct node *h, int i,int size) {
int l = left(i);
int r = right(i);
int m = i;
if (l < size && h[l].value < h[i].value) {
m = l;
}
else if (r < size && h[r].value < h[i].value) {
m = r;
}
if (m != i) {
swap(&h[m].value, &h[i].value);
heapify(h, m, size);
}
}
int left(int i) { return 2 * i; }
int right(int i) { return (2 * i + 1); }
void swap(int *x, int *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}