File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < vector>
3
+ using namespace std ;
4
+ // Max heap
5
+ void upheapify (vector<int > &heap,int idx){
6
+ if (idx==0 ){
7
+ return ;
8
+ }
9
+ int parentidx=(idx-1 )/2 ;
10
+ if (heap[parentidx]<heap[idx]){
11
+ swap (heap[parentidx],heap[idx]);
12
+ upheapify (heap,parentidx);
13
+ }
14
+ else {
15
+ return ;
16
+ }
17
+ }
18
+ void downheapify (vector<int > &heap,int idx){
19
+ int leftidx=2 *idx+1 ;
20
+ int rightidx=2 *idx+2 ;
21
+ if (leftidx>=heap.size () && rightidx>=heap.size ()){
22
+ return ;
23
+ }
24
+ int largestidx=idx;
25
+ if (leftidx<heap.size ()&&heap[leftidx]>heap[idx]){
26
+ largestidx=leftidx;
27
+ }
28
+ if (rightidx<heap.size ()&&heap[rightidx]>heap[idx]){
29
+ largestidx=rightidx;
30
+ }
31
+ if (largestidx==idx){
32
+ return ;
33
+ }
34
+ swap (heap[idx],heap[largestidx]);
35
+ downheapify (heap,largestidx);
36
+
37
+ }
38
+ void buildheap (vector<int > &heap){
39
+ for (int i=0 ;i<heap.size ();i++){
40
+ upheapify (heap,i);
41
+ }
42
+ }
43
+ void buildheapOptimised (vector<int > &heap){
44
+ for (int i=heap.size ()-1 ;i>=0 ;i--){
45
+ downheapify (heap,i);
46
+ }
47
+ }
48
+ // delete peak element
49
+ void deletepeek (vector<int > &heap){
50
+ swap (heap[0 ],heap[heap.size ()-1 ]);
51
+ heap.pop_back ();
52
+ downheapify (heap,0 );
53
+ }
54
+
55
+ void insert (vector<int > &heap,int key){
56
+ heap.push_back (key);
57
+ upheapify (heap,heap.size ()-1 );
58
+ }
59
+ void display (vector<int > heap){
60
+ for (int i=0 ;i<heap.size ();i++){
61
+ cout<<heap[i]<<" " ;
62
+ }
63
+ }
64
+
65
+ int main (){
66
+ vector<int > heap;
67
+ int n;
68
+ cin>>n;
69
+ for (int i=0 ;i<n;i++){
70
+ int x;
71
+ cin>>x;
72
+ heap.push_back (x);
73
+ // insert(heap,x);
74
+ }
75
+ buildheapOptimised (heap);
76
+ display (heap);
77
+ // cout<<endl;
78
+ // deletepeek(heap);
79
+ // display(heap);
80
+
81
+ }
You can’t perform that action at this time.
0 commit comments