You can try to sort yourself or extract only positive values ββand sort them, but here is an alternative version that leaves the input array unmodified (since otherwise returning a new array from the method would be superfluous).
The code simply copies and sorts the input array first, then combines the negative values ββfrom the input array with the positive values ββfrom the sorted array. Since negative values ββwere sorted first, there is no way to overwrite the sorted values ββin a copy.
The code also does not insert values, as would be necessary to build List<Integer> positive values.
private static int[] sortByHeight(int[] inputArray) { int[] arr = inputArray.clone(); Arrays.sort(arr); int i = 0; while (i < arr.length && arr[i] < 0) i++; for (int j = 0; j < arr.length; j++) arr[j] = (inputArray[j] < 0 ? inputArray[j] : arr[i++]); return arr; }
Test
int[] inputArray = {-1, 150, 190, 170, -2, -1, 160, 180}; int[] outputArray = sortByHeight(inputArray); System.out.println(Arrays.toString(outputArray));
Exit
[-1, 150, 160, 170, -2, -1, 180, 190]
Reusing arr for both a sorted array of all values ββand an array of results works because a positive value will only be copied or will remain where it is.
To illustrate:
-1, 150, 190, 170, -2, -1, 160, 180 // Input array β β β β β β β β β -1, 150, 160, 170, -2, -1, 180, 190 // Result array β β βββββββββββ β β β βββββββββββ β β β βββββββββββ β β β β -2, -1, -1, 150, 160, 170, 180, 190 // Array after sorting