Good afternoon, well, I can’t understand in any way what principle works for compare, where I haven’t read it yet.
There is a code
public class Solution { public static void main(String[] args) { Integer[] array = {13, 8, 15, 5, 17}; System.out.println(Arrays.toString(sort(array))); } public static Integer[] sort(Integer[] array) { Arrays.sort(array); final double median; if (array.length % 2 != 0) { median = array[array.length / 2]; } else { median = (array[(array.length / 2 - 1)] + array[(array.length / 2)]) / 2d; } Arrays.sort(array, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { System.out.println("o1 " + o1.toString()); System.out.println("o2 " + o2.toString()); if (o1.equals(o2)) return 0; if (Math.abs(Double.parseDouble(o1.toString()) - median) - Math.abs(Double.parseDouble(o2.toString()) - median) > 0) { return 1; } else if (Math.abs(Double.parseDouble(o1.toString()) - median) - Math.abs(Double.parseDouble(o2.toString()) - median) < 0) { return -1; } else return 0; } }); return array; } } When does it compare the values of an array? I can not understand. Even specially brought the elements:
o1 8 o2 5 o1 13 o2 8 o1 15 o2 13 o1 15 o2 8 o1 15 o2 13 o1 17 o2 8 o1 17 o2 15 That is why he compares 5 only once to 8 and why 8 first, i.e. o1 and 5 second o2 , if in the array after sorting 5 first will be.
Help me please please.
And by some miracle, he eventually brought up [13, 15, 17, 8, 5]