-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path힙과힙정렬_4.c
85 lines (70 loc) · 1.31 KB
/
힙과힙정렬_4.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable : 4996)
#define SIZE 100
typedef struct {
int H[SIZE];
int N;
}Heap;
void init(Heap* heap) {
heap->N = 0;
for (int i = 0; i < SIZE; i++)
heap->H[i] = 0;
}
void insertItem(Heap* heap, int key) {
heap->N++;
heap->H[heap->N] = key;
}
void downHeap(Heap* heap, int i) {
int k = heap->H[i];
int p = i, c = i * 2;
while (c <= heap->N) {
if ((c < heap->N) && (heap->H[c] < heap->H[c + 1]))
c++;
if (heap->H[c] <= k)
break;
heap->H[p] = heap->H[c];
p = c;
c = c * 2;
}
heap->H[p] = k;
}
void BuildHeap(Heap* heap) {
for (int i = heap->N / 2; i >= 1; i--)
downHeap(heap, i);
}
int removeMax(Heap* heap) {
int key = heap->H[1];
heap->H[1] = heap->H[heap->N];
heap->N--;
downHeap(heap, 1);
return key;
}
void inPlaceHeapSort(Heap* heap) {
int size = heap->N;
for (int i = 0; i < size; i++) {
int key = removeMax(heap);
heap->H[heap->N + 1] = key;
}
}
void printArray(Heap* heap, int size) {
for (int i = 1; i <= size; i++)
printf(" %d", heap->H[i]);
printf("\n");
}
int main() {
Heap heap;
init(&heap);
int N;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
int num;
scanf("%d", &num);
insertItem(&heap, num);
}
BuildHeap(&heap);
inPlaceHeapSort(&heap);
printArray(&heap, N);
return 0;
}