0
Comparator<struc> cmp= new Comparator<struc>() {
  public int compare(struc e1, struc e2) {
    return e1.x - e2.x;
  }
};

struc is point structure. when I offer:

(3,1)(3,2)(3,3)(3,4)

q gives me:

(3,1)(3,4),(3,3)(3,2)

and when I offer:

(3,1)(3,3)(3,2)(3,4)

it gives me:

(3,1)(3,4),(3,2)(3,3).

What's the logic?

Should it just give the order of key_in sequence since y is not compared? When I checked API,it tells me "An unbounded priority queue based on a priority heap...The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily."

Can someone help explain?

3
  • 2
    Please add the code of struc, and the code you use to put/retrieve the values in the queue. Are you iterating the values using an Iterator, or are you using poll() to get/remove the head every time ? Commented Mar 6, 2015 at 15:03
  • "Ties are broken arbitrarily" means the PQ can do whatever it wants when it sees a tie, including shuffling your input randomly. Commented Mar 6, 2015 at 16:55
  • I used a poll() method to get/remove the head every time. Struc class is just a point class. Commented Mar 7, 2015 at 4:23

2 Answers 2

2

The order is undefined here because all your points tie with each other since their x co-ordinate values are the same. If you're expecting to have the same order, you should enforce that by modifying your compare() implementation to take into account their y co-ordinate values as well.

And, even if the order was for some reason coming the same, it's incorrect for your program to depend on undefined behaviour for its correctness.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with you it's incorrect for program to depend on undefined behaviour for its correctness. I talked with my friend yesterday, He thought this might have something to do with its heap structure.
1

The answer is in the doc you quoted: "Ties are broken arbitrarily" means the PQ can do whatever it wants when it sees a tie, including shuffling your input randomly.

All of your inputs have the same x coordinate, so they all tie, and the priority queue can deal with that "arbitrarily," meaning in any way it wants, without any guarantees.

2 Comments

I am trying to implement a FIFO method. If they come at the same time, just first come first serve. =.=
Then you have to add another property to the elements indicating the order they came in; there's no other way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.