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>)

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
6 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Seliba
9 months ago

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.

Seliba
9 months ago
Reply to  Niinbo

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

Seliba
9 months ago

It knows that because the elements (Node) Comparable#compareTo() are implemented. The order is set