Search code examples
javasortingarraylistcomparator

Understand how sorting with compare works for an ArrayList in java


I want to understand how the following comparator gives me results in ascending order:

Comparator<Integer> ints = (i1, i2) -> i1 - i2;

How does providing i1-i2 as the implementation give me results in ascending order? Can you please explain in the context of the ArrayList with elements [5, 4, 1, 2]? I am looking for some explanation similar to this: first 1 is compared with 4, the result is 4-1=3, which is a positive number, the current state of arraylist becomes this [4, 5, 1, 2] and so on to get to the final result of [1, 2, 4, 5].

I want to understand the working of the comparator implementation.


Solution

  • I think you wanted to understand how the sorting algorithm uses the comparator internally. So, let's see how Collections.sort() uses Comparator` to sort a list.

    Let's peek into the JDK and see specifically how insertion sort uses comparator.

    This is the JDK code snippet for insertion sort which Collections.sort() uses to sort list with size < 7.

    for (int i=low; i<high; i++){
        for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
            swap(dest, j, j-1);
        }
    
       //remaining logic
    }
    

    We can see that the sorting algorithm uses the c.compare() method to decide the sorting order.

    Suppose this is my comparator function:

    class MyComparator implements Comparator<Integer> {
       @Override
       public int compare(Integer x, Integer y) {
           return x - y;
       }
    }
    

    The sorting algorithm will calculate c.compare(dest[j-1], dest[j]) > 0 for every element. And, it will only swap the left and right value if the above expression is greater than 0. i.e. if x > y OR dest[j-1] > dest[j].

    Thus, after swapping the smaller element in the right comes to left and greater element goes to right side which is basically sorting the list in ascending order.

    If, we do y-x in compare() method, sorting in reverse order(descending order) will occur using similar logic.