I'm using PriorityQueue
and i've implemented comparable class, with compareTo method,
Now i want to know if my queue is sorted, if i use poll()
method will this return the queue of the minimum costSum?
Class: State.java
public class State<N extends Comparable<N>> implements Comparable<State<N>> {
private final ArrayList<Integer> board;
private State<N> predecessor;
private double totalCostFromStart; //g(x)
private double minimumRemainingCostToTarget; //h(x)
private double costSum; //f(x)
private Move direction;
public State(ArrayList<Integer> board,
State<N> predecessor,
double minimumRemainingCostToTarget,
Move direction) {
this.board = board;
this.predecessor = predecessor;
this.totalCostFromStart = predecessor == null ? 0 : predecessor.totalCostFromStart 1;
this.minimumRemainingCostToTarget = minimumRemainingCostToTarget;
this.direction=direction;
calculateCostSum();
}
private void calculateCostSum() {
this.costSum = this.totalCostFromStart this.minimumRemainingCostToTarget;
}
@Override
public int compareTo(State<N> nNode) {
int compare = Double.compare(this.costSum, nNode.costSum);
if (compare == 0) return 0;
else return this.costSum>nNode.costSum ? 1:-1;
}
Class : AStar.java
public State AStar(ArrayList<Integer> initialBoard,
State source,
ArrayList<Integer> target,
Heuristic heuristic){
int minimumRemainingCostToTarget= heuristic.getRank(initialBoard, target);
source = new State( initialBoard,null,0, minimumRemainingCostToTarget,null);
PriorityQueue<State> open = new PriorityQueue<>();
Set<ArrayList<Integer>> close = new HashSet<>(181440);
//add initial state to ouverts, f(n) is an attribut in source.
open.add(source);
while(!close.isEmpty()){
State currentState = open.poll();//<<<----------------------
}
return null;
}
CodePudding user response:
Now i want to know if my queue is sorted, if i use poll() method will this return the queue of the minimum costSum?
The Javadoc describes this:
The head of this queue is the least element with respect to the specified ordering. ... The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
So, yes, it is the minimum element.
Note, however, that the queue isn't internally sorted: if you print a priority queue, you may note that they do not appear in ascending order. The elements are simply stored in an order with the heap property, which allows efficient updating of the data structure once the minimum element is removed.