-
Notifications
You must be signed in to change notification settings - Fork 11
/
heap.cpp
77 lines (58 loc) · 1.32 KB
/
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<bits/stdc++.h>
using namespace std;
void swap(int *a, int *b){
int temp;
temp = *a;
*a=*b;
*b=temp;
}
void heapify (int array[], int n, int current){
int largest = current;
int leftChild = 2*current +1;
int rightChild = 2*current+2;
if(leftChild <n && array[leftChild]>array[largest]){
largest = leftChild;
}
if(rightChild< n && array[rightChild]>array[largest]){
largest = rightChild;
}
if(largest!=current){
swap(array[current],array[largest]);
heapify(array,n,largest);
}
}
void printArray(int array[], int size){
cout << endl;
for(int i=0; i<size;i++){
cout << array[i] << " ";
}
cout << endl;
}
void heapsort(int array[], int size){
for(int i = size -1; i>=0; i--){
swap(array[0], array[i]);
//Print the Array
heapify(array,i,0);
}
}
int main(){
int n;
cin>>n;
int array[n];
for(int i=0; i<n;i++){
cin>>array[i];
}
cout << "Before Heapify: ";
printArray(array,n);
// Heapify
int nonLeafStart =(n/2)-1;
for(int i =nonLeafStart; i>=0; i--){
heapify(array, n, i);
}
cout << "After Heapify: ";
printArray(array,n);
heapsort(array,n);
cout << "After the HeapSort: ";
printArray(array,n);
return 0;
}