• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparator Query !!!  RSS feed

 
Sahil Kapoor
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ref :- Pg 591 Topic : Priority Queue

Priority Queue gives 1 higher priority than 2 , but natural ordering for integers is 1<2. Anyways, may be PQ is implemented that way.
But in order to give priorities such that 9>8....and so on, we used static class and implements Comparator<Integer> .


Query :- Inside static class compare method is implemented in the following way :-




But above code again implies 1>2>3>4>5>6>7>8>9 ...then how does Priority Queue is giving ordering in reverse ie 9>8>7>6>5>4>3>2>1


Let me explain you the way i am thinking .....

compare contratc is as follows

public int copare(object 1, object 2)

if( object 1< Object 2) return negative
if(object1==object2) return zero
if(object 1 > object 2) return positive


Now when we pass 1 and 2 (say) then compare method implemented on the top would give back (2-1) = positive result which
in accordance to above contract implies 1>2 . But we want 2>1 ???

Is this the case that priority queue reverses the order defined ??
Like natural order is 1<2<3<4 but it gives priority in the reverse order ie 1>2>3>4
and when
we defined order to be 1>2>3>4 it gives priority in reverse order ie 1<2<3<4 ???


Thanks !!!

 
Himanshu Mall
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didnt get it. What is your point?
 
Henry Wong
author
Sheriff
Posts: 23292
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ref :- Pg 591 Topic : Priority Queue


It would also help if you provided the name of the book too. Giving just a page number is not very useful.

Henry
 
Gaurav Sainii
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sahil,

As per the compare contract:-
public int compare(object 1, object 2)

if( object 1< Object 2) return negative
if(object1==object2) return zero
if(object 1 > object 2) return positive


and in your code you are specifying :-

This is actually reverse of the compare contract.

suppose you have object1=7 and object2=8 then your compare implementation will return 8-7 (object2-object1) = 1 so it will give order as 9>8>7>6>5>4>3>2>1

but actually as per compare contract you need to return 7-8 (object1-object2) = -1 in case object1 is less than object2.



 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!