-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.c
More file actions
59 lines (55 loc) · 1.03 KB
/
Copy pathheap.c
File metadata and controls
59 lines (55 loc) · 1.03 KB
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
/*********
* Heap Sort
*******/
#include <stdio.h>
#define LEFT(i) (2 * i)
#define RIGHT(i) (2 * i + 1)
#define N 10
void HEAPSORT(int*, int);
void MAX_HEAPIFY(int*, int, int);
void BUILD_MAX_HEAP(int*, int);
int main(void) {
int i, j, n = N, temp, A[] = {4,1,3,2,16,9,10,14,8,7};
for (i = 0; i < N - 1; i++) {
HEAPSORT(A, n);
n--;
temp = A[0];
A[0] = A[n];
A[n] = temp;
}
for (j = 0; j < N; j++) {
printf("%d ", A[j]);
}
printf("\n");
return 0;
}
void HEAPSORT(int A[], int n) {
int i;
BUILD_MAX_HEAP(A, n);
for (i = n; i > 0; i--) {
MAX_HEAPIFY(A, i, n);
}
}
void MAX_HEAPIFY(int A[], int i, int n) {
int l = LEFT(i), r = RIGHT(i), largest, temp;
if (l <= n && A[l - 1] > A[i - 1]) {
largest = l;
} else {
largest = i;
}
if (r <= n && A[r - 1] > A[largest - 1]) {
largest = r;
}
if (largest != i) {
temp = A[i - 1];
A[i - 1] = A[largest - 1];
A[largest - 1] = temp;
MAX_HEAPIFY(A, largest, n);
}
}
void BUILD_MAX_HEAP(int A[], int n){
int i;
for (i = n / 2; i > 0; i--) {
MAX_HEAPIFY(A, i, n);
}
}