-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heapsort.cpp
80 lines (63 loc) · 1.52 KB
/
Heapsort.cpp
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
// 2017029634_¹Ú¼ºÈ¯_12838
#include <stdio.h>
void Max_Heapify(int* Array, int index, int* HeapSize);
void Build_Max_HEAP(int* Array, int* HeapSize);
int Extract_Max(int* Array, int* HeapSize);
int main() {
int N;
int K;
int value;
int* HeapSize;
scanf("%d %d", &N, &K);
int* Array = new int[N];
HeapSize = &N;
for (int i = 0; i < N; i++) {
scanf("%d", &value);
Array[i] = value;
}
Build_Max_HEAP(Array, HeapSize);
for (int i = 0; i < K; i++)
printf("%d ", Extract_Max(Array, HeapSize));
printf("\n");
for (int i = 0; i < *HeapSize; i++)
printf("%d ", Array[i]);
printf("\n");
}
void Max_Heapify(int* Array, int index, int* HeapSize) {
int temp;
int k;
if (index * 2 > * HeapSize)
return;
if (index * 2 == *HeapSize) {
k = index * 2;
if (Array[index - 1] < Array[k - 1]) {
temp = Array[index - 1];
Array[index - 1] = Array[k - 1];
Array[k - 1] = temp;
Max_Heapify(Array, k, HeapSize);
}
}
else {
if (Array[index * 2] > Array[index * 2 - 1]) k = index * 2 + 1;
else k = index * 2;
if (Array[index - 1] < Array[k - 1]) {
temp = Array[index - 1];
Array[index - 1] = Array[k - 1];
Array[k - 1] = temp;
Max_Heapify(Array, k, HeapSize);
}
}
return;
}
void Build_Max_HEAP(int* Array, int* HeapSize) {
for (int i = *HeapSize / 2; i > 0; i--)
Max_Heapify(Array, i, HeapSize);
}
int Extract_Max(int* Array, int* HeapSize) {
int Value = Array[0];
Array[0] = Array[*HeapSize - 1];
Array[*HeapSize - 1] = Value;
(*HeapSize)--;
Max_Heapify(Array, 1, HeapSize);
return Value;
}