-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
delete_peak_elements_in_maxHeap.cpp
124 lines (111 loc) · 2.52 KB
/
delete_peak_elements_in_maxHeap.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
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
/*Problem Statement:
You are given a max heap,
your task is to delete the peak elements from the max heap until the last element is left. */
#include<bits/stdc++.h>
using namespace std;
void upward_heapify(vector<int> &max_heap, int index)
{
if(index==0)
return;
if(max_heap[(index-1)/2] < max_heap[index])
{
int temp = max_heap[index];
max_heap[index] = max_heap[(index-1)/2];
max_heap[(index-1)/2] = temp;
upward_heapify(max_heap, (index-1)/2);
}
else
{
return;
}
}
void insert(vector<int> &max_heap, int key)
{
max_heap.push_back(key);
upward_heapify(max_heap, max_heap.size()-1);
}
void downward_heapify(vector<int> &max_heap, int index)
{
int size = max_heap.size();
if(index>=max_heap.size()/2)
{
return;
}
if(index*2 + 1 >= size)
{
return;
}
if(index*2 + 2 >= size)
{
//If only left child exists
if(max_heap[index*2 + 1] > max_heap[index])
{
swap(max_heap[index*2 + 1], max_heap[index]);
downward_heapify(max_heap, index*2 + 1);
}
}
else
{
// If both child exists
int maxIndex = max_heap[index*2 + 1] > max_heap[index*2 + 2] ? index*2 + 1 : index*2 + 2;
if(max_heap[index] < max_heap[maxIndex])
{
swap(max_heap[index], max_heap[maxIndex]);
downward_heapify(max_heap, maxIndex);
}
}
}
void delete_peak(vector<int> &max_heap)
{
swap(max_heap[0],max_heap[max_heap.size()-1]);
max_heap.pop_back();
downward_heapify(max_heap, 0);
}
void display(vector<int> &max_heap)
{
for(int i=0;i<max_heap.size();i++)
cout<<max_heap[i]<<" ";
cout<<endl;
}
int main()
{
vector<int> max_heap;
int n,temp;
cout<<"Enter total elements: "<<endl;
cin>>n;
cout<<"Enter all elements of max heap: "<<endl;
for(int i=0;i<n;i++)
{
cin>>temp;
insert(max_heap,temp);
}
cout<<"Max heap looks like: "<<endl;
display(max_heap);
for(int i =0;i<n-1;i++)
{
delete_peak(max_heap);
cout<<"After deleting peak element: "<<endl;
display(max_heap);
}
return 0;
}
/*Example:-
Input:-
Enter total elements:
5
Enter all elements of max heap:
1 4 3 2 5
Output:-
Max heap looks like:
5 4 3 1 2
After deleting peak element:
4 2 3 1
After deleting peak element:
3 2 1
After deleting peak element:
2 1
After deleting peak element:
1
Time Complexity: O(nlogn)
Space Complexity: O(nlogn)
*/