| Author |
priority queue!
|
vijay umar
Ranch Hand
Joined: Mar 24, 2009
Posts: 100
|
|
here is one code:
import java.util.*;
class PQ
{
static class PQsort
implements Comparator<Integer> {
public int compare(Integer one, Integer two) {
return two - one; // unboxing
}
}
public static void main(String[] args)
{
int[] ia = {1,5,3,7,6,9,8 }; // unordered data
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(); // use natural order
for(int x : ia) // load queue
pq1.offer(x);
for(int x : ia)
System.out.print(pq1.poll() + " ");
System.out.println("");
PQsort pqs = new PQsort(); // get a Comparator
PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10,pqs); // use Comparator
for(int x : ia) // load queue
pq2.offer(x);
System.out.println("size " + pq2.size());
System.out.println("peek " + pq2.peek());
System.out.println("size " + pq2.size());
System.out.println("poll " + pq2.poll());
System.out.println("size " + pq2.size());
for(int x : ia) // review queue
System.out.print(pq2.poll() + " ");
}
}
in this code i dint understand that how the comparator is working.How does it arrange the elements in the queue?
espicially this one:
[b]implements Comparator<Integer> {
public int compare(Integer one, Integer two) {
return two - one; // unboxing
}
how does this works?please explain!
|
 |
armando fonseca
Ranch Hand
Joined: Apr 03, 2009
Posts: 49
|
|
hi vijay,
look this part carefully,
You are comparing two numbers by subtracting them!
if integer two > than integer one
then it return a positive number , zero if they are equal and a negative number if integer two is less than integer one. Using your code , it will order from highest to lowest if I'm not mistaken( I'm not sure!.... any the order is irrelevant). Then when you are adding the numbers at:
, it will use the sorting algorithm to store the values in the queue rather than using FIFO.
Now I have a question to you vijay, by looking your comparator implementation, is the output: 9,8,7,6,5,3,1 when traversing ?
-Armando
|
scjp6-90%
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
Please Use Code Tags to make your code readable...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Shin Kudo
Greenhorn
Joined: Apr 17, 2009
Posts: 25
|
|
He wants to make the code look like in real SCJP exam
|
SCJP 6 - SCWCD in progress...
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
Shin Kudo wrote:He wants to make the code look like in real SCJP exam
In the real SCJP exam, the code has proper indentation. It's just that the code is jammed into the smallest size possible. So this code would come something like this
|
 |
vijay umar
Ranch Hand
Joined: Mar 24, 2009
Posts: 100
|
|
hi armando ,
nice meeting you
thanks for replying
yes the queue is sorted like that.
|
 |
 |
|
|
subject: priority queue!
|
|
|