Binary Heap
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(int array[], int size, int i)
{
if (size == 1) return;
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
// is left or right branch largest ?
if (left < size && array[left] > array[largest])
largest = left;
if (right < size && array[right] > array[largest])
largest = right;
// if it was, swap with the child and re-apply the process on child
if (largest != i) {
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
void insert(int array[], int newNum, int* size)
{
if (*size == 0) {
array[0] = newNum;
*size += 1;
} else {
array[*size] = newNum;
*size += 1;
for (int i = *size / 2 - 1; i >= 0; i--) {
heapify(array, *size, i);
}
}
}
int extract_max(int max_heap[], int* size) {
if(*size <= 0) return max_heap[0];
int max = max_heap[0];
max_heap[0] = max_heap[*size - 1];
*size -= 1;
heapify(max_heap, *size, 0);
return max;
}
source