Menu
Coddy logo textTech

Practice #4

Lesson 13 of 14 in Coddy's Heaps & Priority Queues - Data Structures Series #7 course.

challenge icon

Challenge

Easy

Write a function heapSort that gets an integer array arr and returns it sorted in ascending order.

heapSort is the canonical use of a min-heap: insert every value into a heap, then extract the minimum until the heap is empty.

You must use the MinHeap class (provided in minheap.<ext>) — do not use language built-ins like sort, slice, or stdlib heap libraries to compute the result.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "solution.h"

int main() {
    char line[8192];
    if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
    int arr[4096];
    int n = 0;
    char* tok = strtok(line, " \t\r\n");
    while (tok) { arr[n++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    int rs = 0;
    int* r = heapSort(arr, n, &rs);
    for (int idx = 0; idx < rs; idx++) { if (idx > 0) printf(" "); printf("%d", r[idx]); }
    printf("\n");
    return 0;
}

All lessons in Heaps & Priority Queues - Data Structures Series #7