-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathheap.cpp
77 lines (66 loc) · 1008 Bytes
/
heap.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
#include<stdio.h>
#define heapSize 7
int a[heapSize];
int parent(int i){
return i/2;
}
int left(int i){
return (2*i);
}
int right(int i){
return ((2*i)+1);
}
int leaf(int l){
return l/2;
}
void printArray(int size){
for(int i=1;i<=size;i++){
printf("%d\t",a[i]);
}
printf("\n");
}
void maxHeapify(int i,int size){
int l=left(i);
int r=right(i);
int largest;
if(l<=size && a[l] > a[i]){
largest=l;
}else{
largest=i;
}
if(r<=size && a[r] > a[largest]){
largest=r;
}
if(largest!=i){
int t=a[largest];
a[largest]=a[i];
a[i]=t;
maxHeapify(largest,size);
}
}
void buildMaxHeap(int s){
for(int i=leaf(s);i>=1;i--){
maxHeapify(i,s);
}
}
void heapSort(int size){
while(size>=1){
printf("%d\t",a[1]);
a[1]=a[size];
size=size-1;
buildMaxHeap(size);
}
}
int main()
{
for(int i=1;i<=heapSize;i++){
a[i]=i;
}
printf("My Array:\n");
printArray(heapSize);
printf("My Sorted Array:\n");
buildMaxHeap(heapSize);
heapSort(heapSize);
printf("\n");
return 0;
}