first time posting here. I am trying to understand how this Java sort method actually sorts the array. I have already used a Java visualizer and it still makes zero sense to me. I understand that the sort method is taking in the array, and then uses two elements at a time to submit them to an expression (the second number minus the first number), but I do not understand how this value is used to sort the array:
Arrays.sort(arrayList,(Integer number1, Integer number2) -> number2 - number1)
(the arrayList elements can be whatever integers you would like)
If comparator function return positive value, numbers will be swapped. => if number2 > number1, then (number2 - number1) > 0 (positive) => swapped => number2 will be placed before and number1.
You can check the detail in function Comparator.compare:
Arrays.sort(values, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o2 > o1) {
return 1; // need swap
} else if (o2 < o1) {
return -1; // no swap
}
return 0; // no swap
}
});
}