Instead of using a MinHeap
that will allow me to change the vertex priorities I am using the Java library PriorityQueue
.
Here is how I have implemented the vertices which will generate the vertex array. Also, I have not maintained any separate array for storing the shortest distance to a vertex from source. Instead, I have a class variable will handle that and more importantly allow the priority queue to sort the elements by implementing a different version of compareTo
method.
class indivisualvertex implements Comparable<indivisualvertex> {
int data; //data associated with the vertex
double distanceFromSource; //will store the distances from the source vertex
int previousVertexOnShortestPathFromSource;//will store the previous vertex on the path
neighbours adjacentPointsList; // neighbouring vertices stored in a linked list
//for sorting the vertices in the priority queue according to their distances from the source
public int compareTo(indivisualvertex other) {
if (this.equals(other)) {
return 0;
} else if (this.distanceFromSource > other.distanceFromSource) {
return 1;
} else {
return -1;
}
}
}
Here's also my implementation for the edge relaxation method used after a vertex is chosen from the priority queue. Since there isn't any method to modify the elements inside of a priority queue, the code picks out the desired vertex, changes its distanceFromSource
and previousVertexOnShortestPathFromSource
variables and then puts it back, sorting the queue in the process.
private void relax(indivisualvertex indx) {
//traverse the neighbouring edges
for (neighbours nbr = indx.adjacentPointsList; nbr != null; nbr = nbr.next){
//condition where a vertex is unvisited and also provides a shorter path
if (visited[nbr.pointer_of_vertex] == false && vertices[nbr.pointer_of_vertex].distanceFromSource > vertices[nbr.from].distanceFromSource + nbr.weight) {
pq.remove(vertices[nbr.pointer_of_vertex]);
vertices[nbr.pointer_of_vertex].distanceFromSource = vertices[nbr.from].distanceFromSource + nbr.weight;
vertices[nbr.pointer_of_vertex].previousVertexOnShortestPathFromSource = nbr.from;
pq.add(vertices[nbr.pointer_of_vertex]);
}
}
}
The implementation works fine. I need to know if there can be any disadvantages to to not building our own minimum heap for this purpose. Also, while relaxing the edges the method extracts the vertex and then puts it back. Is this an expensive operation? How much does it affects the performance of the algorithm?