Menu
Coddy logo textTech

Practice #2

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

challenge icon

Challenge

Easy

Write a function kLargest that gets an integer array arr and an integer k, and returns the k largest values in sorted ascending order.

If k is larger than the array, return all values sorted. If k is zero or negative, return an empty array.

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];
    char tline[64];
    if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
    if (!fgets(tline, sizeof(tline), stdin)) tline[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 k = atoi(tline);
    int rs = 0;
    int* r = kLargest(arr, n, k, &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