I am preparing for OCPJP. While practicing i came across this program. I am not able to understand the logic like what will be passed to String a and String b in the compare method. Can you please help me understand the logic behind this.
You could add a statement like System.out.println(String.format("a=%s, b=%s", a, b)); before line 5. That would tell you what gets passed into that method (which gets called indirectly via the Arrays.sort method).
The compare() method is repeatedly passed two different elements from array you're trying to sort. Which two depends on the sorting algorithm.
Picture this: you and I are both sitting on different sides of a table, with an unsorted row of cards in the middle, face down. Our task is to sort the cards. I only get to see the back of the cards and never the face. You get to see the face of the cards, but you are not allowed to touch them.
We solve the problem like this: I pick two cards from the row and show the faces of the cards to you. You tell me which of the cards is the lesser of the two. I use that information to rearrange those two cards. We repeat this process until I am certain that the entire row is sorted.
In this strange analogy, I am the sort() method, and you are the compare() method.
Stephan van Hulst wrote:The value is picked by the sorting algorithm. You have no control over it. There is no point in trying to find a pattern.
Effectively, every value in the input to be sorted is going to be compared against every other value in the input. Since only once that has been done can we definitively say that the data has all been sorted.
In actuality, we may not need to compare literally every value, since comparison is transitive. We know that if X is less than Y and Y is less than Z, then X must be less than Z.
Because of that, the number of actual calls to the comparator will vary depending on what sort algorithm you use and how well-ordered the data is. And note that if the data was really well-ordered to begin with that the fancier sorts will perform poorly compared to the simpler ones. Every algorithm has its best and worst cases.
Loudly announcing something is true and finding out you're wrong makes you feel foolish.
Finding out you're wrong and refusing to admit it makes you LOOK foolish.