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]

  • one
    Why do you convert numbers to strings and then back to numbers? Did you write this tryndets? - rjhdby
  • No, I pulled this code. Because he himself could not understand how to solve. I just added sout to see System.out.println ("o1" + o1.toString ()); - Vladislav
  • What is your task? Understand specifically in this code (which wrote some kind of pervert) or something else? - rjhdby
  • Here is the task: Implement the logic of the sort method, which should sort the data in the array by distance from its median. Return the sorted array from the minimum distance to the maximum. If the distance is the same for several numbers, then sort them in ascending order. - Vladislav
  • but I’m not going to solve the problem, it was accepted by the validator, I would understand the principle of how compar sorted. But, I think I understood, I wrote the answer below. But if you give another solution, I will be grateful. - Vladislav

1 answer 1

I think I understand how it works. He takes 2 objects.

Общий массив [5, 8, 13, 15, 17] o1 = [8, 13, 15, 17] o2 = [5, 8, 13, 15] And begins to compare o1 = 8 , o2 = 5 . Of course, it's still a mystery why not o1 = [5, 8, 13, 15] , but o2 = [8, 13, 15, 17]

  • why riddle? there is no difference in taking [8, 13, 15, 17] and [5, 8, 13, 15] or vice versa .. here is one of two options and took - keekkenen