It is necessary to write code that copies one array to another as follows: first all elements greater than 0 are copied sequentially, then all elements equal to 0 successively, and then all elements smaller than 0. Successively less than 0. How to do this? Here is my unsuccessful attempt to realize this task:

int[] arr = new int[100]; Random random = new Random(); for (int i = 0; i < arr.length; i++) { int randNum = random.nextInt(800) - 400; arr[i] = randNum; } int[] newArr = new int[100]; int[] positive = new int[100]; int[] negative = new int[100]; int[] zerro = new int[100]; int count = 0; for (int j = 0; j < arr.length; j++) { if (arr[j] > 0) { positive[j] = arr[j]; // System.arraycopy(arr, arr[j], newArr, 0, 100); Not works! } if (arr[j] == 0) { zerro[j] = arr[j]; } if (arr[j] < 0) { negative[j] = arr[j]; } } System.arraycopy(positive, 0, negative, 0, 100); // Not works! System.out.println(Arrays.toString(arr)); System.out.println(Arrays.toString(positive)); System.out.println(Arrays.toString(zerro)); System.out.println(Arrays.toString(negative)); // System.out.println(Arrays.toString(newArr)); 
  • If it's not a secret, where do you get such tasks? - Mikhail Chibel
  • And you would look at debugging through System.out.println right after the declaration of the arrays and before the loop and see what is in them ..... and also during the execution of the loop ..... and also just comment everything separately and leave for example only System.out.println(Arrays.toString(positive)); ......... what will lead? ........... is a hint .......................... and also copying from positive to negative .... ...... this does not seem to be a good idea ....... System.arraycopy(positive, 0, negative, 0, 100); // Not works! System.arraycopy(positive, 0, negative, 0, 100); // Not works! .... how it works .... just why did you decide that it doesn't work? - Alexey Shimansky
  • And if you do not care which way to go, but to achieve the result, then you can simply write Arrays.sort(arr); and the initial array will be sorted)) tutorialspoint.com/java/util/arrays_sort_int.htm - Alexey Shimansky

1 answer 1

To do this, you need to create your own implementation (version) of the Comparator<Integer> interface and override the compare method:

 private class CustomComparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { if (o1 > 0 & o2 != 0) { return o1 - o2; } if (o1 > 0 & o2 == 0) { return -1; } if (o1 < 0 & o2 < 0) { return o2 - o1; } if (o1 < 0 & o2 >= 0) { return 1; } if (o1 == 0) { return o2; } return 0; } 

And then use it on your own. For example:

 CustomComparator customComparator = new CustomComparator(); List<Integer> sortedList = Stream.of(12, 1, 3, 4, 5, 0, 18, 0, -123, -22, -23).sorted(customComparator).collect(Collectors.toList());