-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminheap.c
More file actions
97 lines (76 loc) · 1.48 KB
/
Copy pathminheap.c
File metadata and controls
97 lines (76 loc) · 1.48 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
#include<stdio.h>
#include<stdlib.h>
int insert(int* A, int index, int element)
{
A[index]=element;
// printf("%d %d \n", index, element);
if(index==0)
{
A[0]=element;
}
else if(element<A[(index-1)/2]){
A[index]=A[(index-1)/2];
insert(A, (index-1)/2, element);
}
if(index==0)
{
return 1;
}
return index%2==0?2*(index-1)+1:index+1;
}
void minHeapify(int *A, int i, int N)
{
// printf("%d\n", i);
int smallest=i;
if(2*i+1<N){
if(A[smallest]>A[2*i+1]){
smallest=2*i+1;
}
}
if(2*i+2<N)
{
if(A[smallest]>A[2*i+2])
{
smallest=2*i+2;
}
}
int t=A[i];
A[i]=A[smallest];
A[smallest]=A[i];
if(smallest!=i)
{
minHeapify(A, smallest, N);
}
}
int delete(int* A, int index, int N)
{
index=(index-1)/2;
A[0]=A[index];
minHeapify(A, index, N);
return index-1;
}
void array_insert(int* A, int N)
{
for(int i=N/2; i>=0; i--)
{
minHeapify(A, i, N);
}
}
int main(){
int A[3]={2, 1, 3};
int pqueue[3];
int index=0;
for(int i=0; i<3; i++)
{
index=insert(pqueue, index, A[i]);
}
// for(int i=0; i<3; i++)
// {
// printf("%d ", pqueue[i]);
// }
//printf("%d\n", pqueue[0]);
index=delete(pqueue, index, 3);
printf("%d\n", pqueue[0]);
array_insert(A, 3);
printf("%d\n", A[0]);
}