Menu
CoddyTech

练习 #4

Coddy 堆与优先队列:数据结构系列 #7 课程的第 13 课,共 14 课。

challenge icon

挑战

简单

编写一个函数 heapSort,接收一个整数数组 arr,并返回按升序排序后的数组。

heapSort 是最小堆的典型用法:将每个值插入堆中,然后不断提取最小值,直到堆为空。

你必须使用 MinHeap 类(在 minheap.<ext> 中提供),不要使用语言内置功能(如 sort、slice)或标准库堆库来计算结果。

亲手试试

#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;
}

堆与优先队列:数据结构系列 #7中的所有课

自己练习: C 在线编译器