Example 1: heapify in c
// Max-Heap data structure in C
#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(int array[], int size, int i)
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
}
void insert(int array[], int newNum)
{
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);
}
}
}
void deleteRoot(int array[], int num)
{
int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}
swap(&array[i], &array[size - 1]);
size -= 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int array[10];
insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);
printf("Max-Heap array: ");
printArray(array, size);
deleteRoot(array, 4);
printf("After deleting an element: ");
printArray(array, size);
}
Example 2: heap sort
// @see https://www.youtube.com/watch?v=H5kAcmGOn4Q
function heapify(list, size, index) {
let largest = index;
let left = index * 2 + 1;
let right = left + 1;
if (left < size && list[left] > list[largest]) {
largest = left;
}
if (right < size && list[right] > list[largest]) {
largest = right;
}
if (largest !== index) {
[list[index], list[largest]] = [list[largest], list[index]];
heapify(list, size, largest);
}
return list;
}
function heapsort(list) {
const size = list.length;
let index = ~~(size / 2 - 1);
let last = size - 1;
while (index >= 0) {
heapify(list, size, --index);
}
while (last >= 0) {
[list[0], list[last]] = [list[last], list[0]];
heapify(list, --last, 0);
}
return list;
}
heapsort([4, 7, 2, 6, 4, 1, 8, 3]);