i'm reading about the heap data structure, and i can't figure out when to use max heapify function and why.
I wrote a insert function that will always keep the heap a max-heap and i can't see when will max-heapify ever be used.
Can you please explain? Thank you
this is my code:
int PARENT(int i) {
return i/2;
}
int LEFT(int i) {
return 2*i;
}
int RIGHT(int i ) {
return 2*i +1;
}
void max_heapify(int *v, int index, int heapsize) {
int largest;
int left = LEFT(index);
int right = RIGHT(index);
if (left<heapsize && v[left] > v[index])
largest = left;
else
largest = index;
if (right < heapsize && v[right] > v[largest])
largest = right;
if (largest !=index) {
v[index] = v[index] ^v[largest];
v[largest] = v[index] ^v[largest];
v[index] = v[index] ^v[largest];
max_heapify(v,largest,heapsize);
}
}
void insert(int *v, int * length, int value) {
v[++*length] = value;
int valuePos = *length;
int parent = PARENT(valuePos);
if (parent!=valuePos) {
while (v[parent] < v[valuePos]) {
v[parent] = v[parent] ^ v[valuePos];
v[valuePos] = v[parent] ^v[valuePos];
v[parent] = v[parent] ^ v[valuePos];
valuePos = parent;
parent = PARENT(valuePos);
}
}
}
The heapify algorithm should be used when turning an array into a heap. You could do that by inserting each array element in turn into a new heap, but that would take O(n lg n) time, while heapify does it in O(n) time.