Implement Dijkstra algorithm, sort priority queue according to the lowest cost in the queue?
So, I want to sort my queue so that the costs of the nodes in the queue are in ascending order. My class Node implements Comparable<Node>, which would allow comparison by cost, but not immediate sorting.
So my question now is how do I sort the elements within the queue, because what I'm trying to do is find the element with the lowest cost and then save it to a node, but I think that misses the point of the priority queue
private static Node decideNextMarked(PriorityQueue<Node> queue) { Node bestOption = null; if (queue.size() > 1) { for (Node possibleCandidate : queue) { for (Node comparison : queue) { switch (possibleCandidate.compareTo(comparison)) { case -1: bestOption = possibleCandidate; case 1: bestOption = comparison; case 0: } } } } return bestOption; }
What I still do is when inserting the costs into the int[] distance, add the nodes of the queue that are in the unvisited (ArrayList<Node>)
A PriorityQueue is actually already sorted by itself, and not simply a collection of weighted objects. The sorting can happen when inserting or reading.
Is that your own PriorityQueue class or where does it come from? If it is from the JDK, you should Javadocs Look. You can specify a comparator in the constructor if you do not like the natural order. Otherwise, you could also have your nodes implemented Comparable.
that’s in the Node class
Then I don’t understand the problem. The PriorityQueue is sorted and you will get the lowest-quality element with PriorityQueue#poll() (or PriorityQueue#peek(), if you don’t want to remove it automatically). This is all in the above linked Javadocs
and the PriorityQueue is from the JDK
It knows that because the elements (Node) Comparable#compareTo() are implemented. The order is set
I didn’t know exactly where the queue wants to know if I want an ascending order or descending order… well I’m jz so much or less done with it, I’ve done a big deal, but there was a tiny thing of the nen error caused, I’ve found part but not the solution to it…