forked from SumedhArani/Traffic-simulation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpQueue.java
More file actions
125 lines (109 loc) · 2.24 KB
/
pQueue.java
File metadata and controls
125 lines (109 loc) · 2.24 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
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
class element
{
private int vertex;
private int weight;
element(int v, int w)
{
this.vertex =v;
this.weight =w;
}
public int getVertex()
{
return vertex;
}
public int getWeight()
{
return weight;
}
public void setValues(int v, int w)
{
vertex =v;
weight =w;
}
}
public class pQueue
{
private element[] q;
private int size;
private int count;
public pQueue(int sz)
{
q=new element[sz];
size=sz;
count=0;
}
public void display()
{
System.out.println();
for(int i=0;i<count;i++)
{
System.out.print(" "+ q[i].getVertex());
System.out.print(","+ q[i].getWeight());
System.out.print("---");
}
}
public boolean isEmpty()
{
if (count==0)
return true;
else
return false;
}
public element getMin()
{
element 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
{
element 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].getWeight()<=q[i].getWeight())
i++; //index position now goes to the right child
}
if (key.getWeight()>q[i].getWeight()) //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 replace(int v, int w)
{
for(int i=0; i<count; i++)
{
if(v==q[i].getVertex())
q[i].setValues(v,w);
}
}
public void insert(int v, int w)
{
int i,j;
element temp=new element(v,w);
q[count++] =temp; //insert at the end of the heap
i =count-1;
j =(i-1)/2; //find parent of the inserted element
while(i>0 && temp.getWeight()<q[j].getWeight()) //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]= temp; //inserting the key in it's right place
}
}