I am trying to understand when does elements in a list swap during sorting process . So far my understanding is during comparison when we return -1 or 0 no swapping happens and when we return 1 swapping happens. Here is the code
public class ArraySort {
public static void main(String[] args) {
Integer [] input = {1,10};
List<Integer> inputList =Arrays.asList(input);
Collections.sort(inputList,(a,b)->a>b?-1:1);
System.out.println(inputList);
}
}
Returns [10,1] ---- I understand this. Since we are returning 1 from comparison swapping happens.
public class ArraySort {
public static void main(String[] args) {
Integer [] input = {1,10};
List<Integer> inputList =Arrays.asList(input);
Collections.sort(inputList,(a,b)->a>b?1:-1);//changed the signs
System.out.println(inputList);
}
}
Returns [1,10] -- I understand this as no swapping happens since returning -1.
public class ArraySort {
public static void main(String[] args) {
Integer [] input = {1,10};
List<Integer> inputList =Arrays.asList(input);
Collections.sort(inputList,(a,b)->a>b?-1:-1); // both are negative.
System.out.println(inputList);
}
}
Returns [10,1] -- I DON'T understand this as why swapping happens since returning -1 should not cause swapping right? Please clarify my misunderstanding.
Again i tried posts on this forum but could get a satisfactory answer on my question. Return type from a Comparator