-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.c
More file actions
124 lines (110 loc) · 2.25 KB
/
heap.c
File metadata and controls
124 lines (110 loc) · 2.25 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <stdio.h>
int heapSize;
void buildHeap(int *A);
void heapify(int *A, int i);
void swap(int *x, int *y);
void print(int *A);
void heapSort(int *A);
int main(int argc, char *argv[])
{
int A[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
print(A);
heapSort(A);
print(A);
return 0;
}
void print(int *A)
{
int i;
for(i=0;i<length(A);i++)
printf("%d ",A[i]);
printf("\n");
}
int length(int *A)
{
int i=0;
while(A[i])
i++;
return i;
}
void heapSort(int *A)
{
int i;
buildHeap(A);
for (i = length(A);i > 1;i--)
{
swap(&A[1], &A[i]);
heapSize--;
heapify(A,0);
}
}
int heapExtractMax(int *A)
{
int max;
if(heapSize < 1)
{
printf("Heap underflow: %d\n", heapSize);
return -1;
}
max = A[1];
A[1] = A[heapSize];
heapSize--;
heapify(A,1);
return max;
}
void heapInsert(int *A, int key)
{
heapSize++;
int i = heapSize;
while (i > 0 && A[parent(i)] < key)
{
A[i] = A[parent(i)];
i = parent(i);
}
A[i] = key;
}
void buildHeap(int *A)
{
int i;
heapSize = length(A);
for(i=length(A)/2; i >= 0; i--)
heapify(A, i);
}
void heapify(int *A, int i)
{
int largest;
int l = left(i);
int r = right(i);
if (l <= heapSize && A[l]>A[i])
largest = l;
else
largest = i;
if (r <= length(A)&& A[r] > A[largest])
largest = r;
if(largest != i)
{
swap(&A[i], &A[largest]);
heapify(A, largest);
}
}
int parent(int i)
{
return (i / 2);
}
int left(int i)
{
return 2*i;
}
int right(int i)
{
return ((2*i) + 1);
}
void swap(int *x, int *y)
{
int tmp;
printf("before swap x is %d y is %d\n",*x,*y);
tmp = *x;
*x = *y;
*y = tmp;
printf("after swap x is %d y is %d\n",*x,*y);
}