#include <stdio.h>
int n = 9;
int heap[9] = {7,6,5,8,3,5,9,1,6};
int main(void){
// 먼저 전체 트리 구조를 최대 힙 구조로 바꿉니다.
for (int i = 1;i < n;i++){
int c = i;
do{
int root = (c-1)/2;
if (heap[root] < heap[c]){
int temp = heap[c];
heap[c] = heap[root];
heap[root] = temp;
}
c = root;
}while (c != 0);
}
return 0;
}
// 크기를 줄여가며 반복적으로 힙 구성
for (int i = n-1; i>=0;i--){
// 크기가 젤 큰 값을 힙의 맨 뒤로 보냄
int temp = heap[0];
heap[0] = heap[i];
heap[i] = temp;
int root = 0;
int c = 1;
do {
c = 2 * root + 1;
// 자식 중에 더 큰 값 찾기
if (heap[c] < heap[c+1] && c < i - 1){
c++;
}
// 루트보다 지식이 더 크다면 교환
if (heap[root] < heap[c] && c < i){
int temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < i);
}
int temp = heap[0];
heap[0] = heap[i];
heap[i] = temp;
int root = 0;
int c = 1;
do {
c = 2 * root + 1;
// 자식 중에 더 큰 값 찾기
if (heap[c] < heap[c+1] && c < i - 1){
c++;
}
// 루트보다 지식이 더 크다면 교환
if (heap[root] < heap[c] && c < i){
int temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < i);
while ( c < i )
시간 복잡도는 결과적으로 O(nlogn)이 소요된다. N개의 숫자로 힙을 구성할 때, 발생하는 연산도이다. 단순히 이분탐색 트리를 탐색하는데 걸리는 시간은 logn이다. 하지만 이러한 이분탐색트리로 힙을 총 N번 만들기 때문에 이는 O(nlogn)의 시간이 소요되는 것이다.
#include <stdio.h>
int n = 9;
int heap[9] = {2,3,4,5,6,7,8,9,10};
int main(void){
// 먼저 전체 트리 구조를 최대 힙 구조로 바꿉니다.
for (int i = 1;i < n;i++){
int c = i;
do{
int root = (c-1)/2;
if (heap[root] < heap[c]){
int temp = heap[c];
heap[c] = heap[root];
heap[root] = temp;
}
c = root;
}while (c != 0);
}
// 크기를 줄여가며 반복적으로 힙 구성
for (int i = n-1; i>=0;i--){
// 크기가 젤 큰 값을 힙의 맨 뒤로 보냄
int temp = heap[0];
heap[0] = heap[i];
heap[i] = temp;
int root = 0;
int c = 1;
do {
c = 2 * root + 1;
// 자식 중에 더 큰 값 찾기
if (heap[c] < heap[c+1] && c < i - 1){
c++;
}
// 루트보다 지식이 더 크다면 교환
if (heap[root] < heap[c] && c < i){
int temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < i);
}
for (int i = 0;i<n;i++){
printf("%d ", heap[i]);
}
return 0;
}