-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriority_queue_new.c
161 lines (132 loc) · 2.57 KB
/
priority_queue_new.c
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
150
151
152
153
154
155
156
157
158
159
160
161
#include<stdio.h>
#include<stdlib.h>
typedef struct minheap
{
int *arr;
int capacity;
int size;
}minheap;
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void create(minheap *h,int c)
{
h->capacity=c;
h->arr=(int *)malloc(h->capacity*sizeof(int));
h->size=0;
}
int left(int i)
{
return (2*i+1);
}
int right(int i)
{
return (2*i+2);
}
int parent(int i)
{
return ((i-1)/2);
}
void insert(minheap *h,int data)
{
if(h->size==h->capacity)
{
printf("Heap Full\n");
return;
}
h->size++;
h->arr[h->size-1]=data;
for(int i=h->size-1;i!=0 && h->arr[parent(i)]>h->arr[i];)
{
swap(&h->arr[parent(i)],&h->arr[i]);
i=parent(i);
}
}
void minHeapify(minheap *h,int i)
{
int lt=left(i);
int rt=right(i);
int smallest=i;
if(lt<h->size && h->arr[lt]<h->arr[i])
smallest=lt;
if(rt<h->size && h->arr[rt]<h->arr[smallest])
smallest=rt;
if(smallest!=i)
{
swap(&h->arr[smallest],&h->arr[i]);
minHeapify(h,smallest);
}
}
int extractMin(minheap *h)
{
if(h->size==0)
return 999;
if(h->size==1)
{
h->size--;
return h->arr[0];
}
swap(&h->arr[0],&h->arr[h->size-1]);
minHeapify(h,0);
return h->arr[h->size];
}
void buildHeap(minheap *h)
{
for(int i=(h->size-2)/2;i>=0;i--)
{
minHeapify(h,i);
}
}
void display(minheap *h)
{
for(int i=0;i<h->size;i++)
{
printf("%d ",h->arr[i]);
}
printf("\n");
}
int main()
{
minheap h;
int c;
int opt;
int n;
int ele;
printf("Enter the capacity\n");
scanf("%d",&c);
create(&h,c);
do
{
printf("Enter the option\n");
printf("1.buildheap\t2.insert\t3.extract Minimum\t4.display\t0.exit\n");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&h.arr[i]);
}
buildHeap(&h);
printf("heap built succesfully\n");
break;
case 2:printf("Enter the element\n");
scanf("%d",&ele);
insert(&h,ele);
break;
case 3:printf("The deleted element is: %d\n",extractMin(&h));
break;
case 4:printf("The heap:\n");
display(&h);
break;
case 5:
break;
}
}while(opt!=0);
}