-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpQue.java
More file actions
78 lines (70 loc) · 1.51 KB
/
pQue.java
File metadata and controls
78 lines (70 loc) · 1.51 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
public class pQue
{
private int[] q;
private int size;
private int count;
public pQue(int sz)
{
q=new int[sz];
size=sz;
count=0;
}
public void display()
{
System.out.println();
for(int i=0;i<count;i++)
{
System.out.print(" "+ q[i]);
System.out.print(","+ q[i]);
System.out.print("---");
}
}
public int getMin()
{
int t;
t=q[0];
q[0]=q[count-1]; //shift the last element to the first
count--; // decrease the size of the heap
adjust(); //recreating the minimum heap
return t;
}
public void adjust() //trickle down
{
int key;
int j=0;
key =q[j]; //root
int i=2*j+1; //left child
while(i<=count-1)
{
if((i+1)<=count-1) //i+1 =2*j+2 => right child
{
if(q[i+1]<=q[i])
i++; //index position now goes to the right child
}
if (key>q[i]) //trickle down
{
q[j]=q[i]; //moving the child up as it's a min heap
j=i; //the key has the index now of the child that has been moved up
//earlier child's postion is now the parent
i=2*j+1;
}
else
break;
}
q[j]=key; //finally insert the child in its' rightful place
}
public void insert(int key)
{
int i,j;
q[count++] =key; //insert at the end of the heap
i =count-1;
j =(i-1)/2; //find parent of the inserted element
while(i>0 && key<q[j]) //if key<parent => trickle up
{
q[i]=q[j]; //move the parent down
i=j;
j=(i-1)/2; //find the new parent
}
q[i]= key; //inserting the key in it's right place
}
}