Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the order induced by the comparator in Java?

I was so confused about comparator and Collections.sort() in Java. I don't understand the order induced by the comparator. I don't clear about which number the compare function should return to get the sorting direction. I also don't know how Collections will use that compare result to sort the input data. Should I learn them by heart? Is there anything easier to understand them? Can anybody explain it for me? Thanks.

public int compare(Obj a, Obj b){ 
    if(a.age > b.age) return 1; 
    if(a.age < b.age) return -1;
    else              return 0;
}

Update

After received some explanations from some friendly Software Engineer, I understood that the comparator define the order of elements in a Collections. For example, when compare a and b, if the comparator return -1 then a should be put before b in the list.

like image 936
Minh Tri Le Avatar asked Oct 20 '25 08:10

Minh Tri Le


1 Answers

Key thing to remember is if comparison returns positive value ( >0) swap happens. Otherwise not during sorting algorithm.

Example:

4(a) 2(b) 6

For ascending order:

a > b (4 > 2) return 1 (swap requires between a and b i.e place 2 4 6)

For descending order:

a > b ( 2 > 4 ) return -1 (swap not needed between a and b i.e place 4 2 6, because it is already in order).

This logic is implemented under the sorting algorithm. So, if a and b are already in order as you expected, then return -1; otherwise, return 1.

like image 162
Bharatesha M Avatar answered Oct 21 '25 23:10

Bharatesha M