-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP17_Priority_Queue.cpp
149 lines (125 loc) · 2.7 KB
/
P17_Priority_Queue.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int Parent(int i){
if(i%2==0)
return(i/2)-1;
else
return (i/2);
}
int left(int i){
return 2*i+1;
}
int right(int i){
return 2*i+1;
}
void swap(int *a,int *b){
int temp =*a;
*a = *b;
*b =temp;
}
void Max_Heapify(int a[],int n,int i)
{
int largest=i;
int l=2*i+1;
int r=2*i+2;
if (l<n &&a[l]>a[largest])
largest=l;
if (r<n && a[r]>a[largest])
largest=r;
if (largest !=i)
{
swap(&a[largest],&a[i]);
Max_Heapify(a,n,largest);
}
}
void Build_Maxheap(int arr[],int n){
for(int i=(n/2)-1;i>=0;i--){
Max_Heapify(arr,n,i);
}
}
int Max(int arr[]){
return arr[0];
}
int Extract_Max(int arr[],int l){
if (l<1){
cout<<"Underflow"<<endl;
}
int max=arr[0];
arr[0]=arr[l];
l=l-1;
Max_Heapify(arr,l,0);
return max;
}
void Increase_Key(int arr[],int i,int key){
if(key<arr[i]){
cout<<"Error"<<endl;
}
arr[i]=key;
while(i>0 && arr[Parent(i)]<arr[i]){
swap(&arr[i],&arr[Parent(i)]);
i=Parent(i);
}
}
void Insert(int arr[],int l,int key){
l=l+1;
arr[l-1]=INT_MIN;
Increase_Key(arr,l,key);
}
void heap_delete(int arr[],int i,int n)
{
if(arr[i]<arr[n-1])
{
Increase_Key(arr,i,arr[n-1]);
n--;
}
else
{
arr[i]=arr[n-1];
n--;
Max_Heapify(arr,n,i);
}
}
int main(){
cout<<"Enter size of array..."<<endl;
int n;
cin>>n;
int arr[n];
cout<<"Enter elements.."<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
//1)Finding maximum element...
// Build_Maxheap(arr,n);
// cout<<"Maximum element is..."<<endl;
// cout<<Max(arr)<<endl;
//2)Extracting max heap...
// cout<<"Extracting maximum element in heap..."<<endl;
// Build_Maxheap(arr,n);
// cout<<Extract_Max(arr,n)<<endl;
// for(int i=0;i<n;i++){
// cout<<arr[i]<<" ";
// }
//3)Increase key...
// cout<<"Increase key..."<<endl;
// Enter size of array...
// 9
// Enter elements..
// 16 14 10 8 7 9 3 2 4 1
// Increase_Key(arr,8,15);
// for(int i=0;i<n;i++){
// cout<<arr[i]<<" ";
// }
//4)Insert ...
// cout<<"Inserting key"<<endl;
// Insert(arr, 12,10);
// for(int i=0;i<n;i++){
// cout<<arr[i]<<" ";
// }
//5)Delete...
// cout<<"Deleting element..."<<endl;
// heap_delete(arr,2,n);
// for(int i=0;i<n;i++){
// cout<<arr[i]<<" ";
// }
}