Practice #4
Coddy의 힙 & 우선순위 큐 - 자료구조 시리즈 #7 코스 레슨 — 14개 중 13번째.
챌린지
쉬움정수 배열 arr를 입력받아 이를 오름차순으로 정렬하여 반환하는 heapSort 함수를 작성하세요.
heapSort는 최소 힙(min-heap)의 전형적인 활용 사례입니다. 모든 값을 힙에 삽입한 다음, 힙이 빌 때까지 최솟값을 추출합니다.
반드시 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;
}