-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheaps.cpp
More file actions
115 lines (104 loc) · 2.35 KB
/
heaps.cpp
File metadata and controls
115 lines (104 loc) · 2.35 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
#include<iostream>
using namespace std;
class heap{
public:
int arr[100];
int size;
heap(){
arr[0] = -1;
size = 0;
}
void insert(int val){
size += 1;
int index = size;
arr[index] = val;
while(index>1){
int parent = index/2;
if(arr[index] > arr[parent]){
swap(arr[index],arr[parent]);
index = parent;
}
else{
return;
}
}
}
void deleteFromHeap(){
if(size == 0){
return ;
}
arr[1] = arr[size];
int i = 1;
size--;
cout << "Deleting from heap..." << endl;
while(i < size){
int leftIndex = 2*i;
int rightIndex = 2*i + 1;
if(leftIndex<size && arr[leftIndex] > arr[i]){
swap(arr[leftIndex],arr[i]);
i = leftIndex;
}
else if(rightIndex<size && arr[rightIndex] > arr[i]){
swap(arr[rightIndex],arr[i]);
i = rightIndex;
}
else{
return;
}
}
}
void print(){
for(int i = 1; i<=size; i++){
cout << arr[i] << " ";
}
cout << endl;
}
};
void heapify(int arr[],int n, int i){
int largest = i;
int left = 2*i;
int right = 2*i + 1;
if(left < n && arr[largest]<arr[left])
largest = left;
if(right < n && arr[largest]<arr[right])
largest = right;
if(largest != i){
swap(arr[largest],arr[i]);
heapify(arr,n,largest);
}
}
void heapSort(int arr[],int n){
while(n > 1){
swap(arr[1],arr[n]);
n--;
heapify(arr,n,1);
}
}
int main(){
// heap h;
// h.insert(23);
// h.insert(40);
// h.insert(55);
// h.insert(70);
// h.insert(30);
// h.insert(60);
// h.print();
// h.deleteFromHeap();
// h.print();
int arr[6] = {-1, 54,53,55,52,50};
int n = 5;
for(int i = n/2; i > 0; i--){
heapify(arr,n,i);
}
cout << "Printing the array now: " << endl;
for(int i = 1; i<=n;i++){
cout << arr[i] <<" ";
}
cout << endl;
cout << "sorted array " << endl;
heapSort(arr,n);
for(int i = 1; i<=n;i++){
cout << arr[i] <<" ";
}
cout << endl;
}