Skip to content

Heapsort

cpp
#include <stdio.h>

void exchange(int* arr, int a, int b) {
    int c = arr[a];
    arr[a] = arr[b];
    arr[b] = c;
}

void printBinaryheap(int* arr, int size) {
    int i = 0, a = 0, b = 0;
    while (i < size) {
        printf("%d ", arr[i++]);
        if (++b >= a * 2) {
            printf("\n"); a = b; b = 0;
        }
    }
    printf("\n");
    printf("----------------\n");
}

void printArray(int* p, int size) {
    printf("{");
    for (int i = 0; i < size; i++) {
        printf("%d", p[i]);
        if (i != size - 1) {
            printf(",");
        }
    }
    printf("}\n");
    printf("----------------\n");
}

//1 2 ^ 0           0
//2 2 ^ 1       1        2
//3 2 ^ 2     3  4    5     6
//4 2 ^ 3   7 8 9 10 11 12 13 14

int isSideNodeMatch(int* arr, int size, int node, int side) {
    if (side >= size || (side < size && arr[side] <= arr[node])) {
        return 1;
    } return 0;
}
int isAllNodeMatch(int* arr, int size, int node) {
    int left = 2 * node + 2;
    int right = left + 1;
    if (isSideNodeMatch(arr, size, node, left) && isSideNodeMatch(arr, size, node, right)) {
        return 1;
    } return 0;
}

void buildMaxheap(int* arr, int size) {
    for (int node = size / 2 - 1; node >= 0; node--) {
        int left = 2 * node + 1;
        int right = left + 1;
        if (!isSideNodeMatch(arr, size, node, left)) {
            exchange(arr, node, left);
            if (left < size && !isAllNodeMatch(arr, size, left)) {
                buildMaxheap(arr, size);
            }
        }
        if (!isSideNodeMatch(arr, size, node, right)) {
            exchange(arr, node, right);
            if (right < size && !isAllNodeMatch(arr, size, right)) {
                buildMaxheap(arr, size);
            }
        }
    }
}

void makeSort(int* arr, int size) {
    // down adjust
    while (--size) {
        exchange(arr, 0, size);
        buildMaxheap(arr, size);
    }
}

int main()
{
    int arr[12] = { 0, 11, 2, 333, 4, 55, 6, 777 ,8, 99, 82, 99 };
    int size = sizeof(arr) / sizeof(int);

    printArray(arr, size);

    printBinaryheap(arr, size);

    buildMaxheap(arr, size);
    printBinaryheap(arr, size);

    makeSort(arr, size);
    printBinaryheap(arr, size);

    printArray(arr, size);
}

Released under the MIT License.