I have made a priorityqueue which inserts objects and compares them with cost parameter ,when two costs are equal it should keep them in enqueued order,but i found after debugging one time it is in enqueued order and other time it is not in the order but i am not getting what is wrong with my code
Output is
0 8 366564
1 3 368282
2 9 368282
4 9 368282
5 9 372423
1 9 372423
0 9 376564
4 10 378282
2 10 378282
7 0 378282
0 4 382423
0 3 436564
but i am expecting
0 8 366564
2 9 368282
1 3 368282
4 9 368282
1 9 372423
5 9 372423
0 9 376564
7 0 378282
2 10 378282
4 10 378282
0 4 382423
0 3 436564
Code:
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; class node implements Comparable < node > { int x; int y; int dir; node(int x, int y, int dir) { this.x = x; this.y = y; this.dir = dir; } public int compareTo(node o) { if (Ideone.cost[o.x][o.y] == Ideone.cost[x][y]) return 1; else { int d = Ideone.cost[x][y] - Ideone.cost[o.x][o.y]; if (d > 0) return 1; else return -1; } } } /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static int[][] cost; static PriorityQueue < node > p; public static void main(String[] args) throws java.lang.Exception { p = new PriorityQueue < node > (); cost = new int[13][11]; for (int[] row: cost) Arrays.fill(row, -1); cost[0][8] = 366564; cost[2][9] = 368282; cost[1][3] = 368282; cost[4][9] = 368282; cost[0][9] = 376564; cost[1][9] = 372423; cost[5][9] = 372423; cost[0][3] = 436564; cost[7][0] = 378282; cost[2][10] = 378282; cost[4][10] = 378282; cost[0][4] = 382423; p.add(new node(0, 8, 8)); p.add(new node(2, 9, 8)); p.add(new node(1, 3, 7)); p.add(new node(4, 9, 2)); p.add(new node(0, 9, 8)); p.add(new node(1, 9, 8)); p.add(new node(5, 9, 2)); p.add(new node(0, 3, 6)); p.add(new node(7, 0, 3)); p.add(new node(2, 10, 8)); p.add(new node(4, 10, 2)); p.add(new node(0, 4, 7)); while (p.size() != 0) { node n1 = p.poll(); System.out.println(n1.x + " " + n1.y + " " + cost[n1.x][n1.y]); } } }
0 8 366564
1 3 368282
2 9 368282
4 9 368282
5 9 372423
1 9 372423
0 9 376564
4 10 378282
2 10 378282
7 0 378282
0 4 382423
0 3 436564
but i am expecting
0 8 366564
2 9 368282
1 3 368282
4 9 368282
1 9 372423
5 9 372423
0 9 376564
7 0 378282
2 10 378282
4 10 378282
0 4 382423
0 3 436564