I am given an array, and I would like to find the position of these elements in the sorted version of the array. So, the input and output would look like as follows
Input : {10, 5, 4, 9, 8, 3, 2, 1, 6, 7}
Output: {0, 3, 4, 9, 8, 1, 2, 5, 6, 7}
This means that, 10 would be at 0th position in the sorted array, and 5, would be in the fourth index, ie sortedinput[3].
Here is a one-liner which does it
Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));
The method would look as follows
public Integer[] findIndexInSortedArray(int[] nums) {
Integer[] index = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
index[i] = i;
}
Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));
return index;
}
Is there a way, to do the same as above, without using lambdas, and any of the features of Java 8? Is it possible to achieve this, using only a Comparator?
10is0th? Shouldn't it be9th3is1st? His final array is{10, 3, 2, 5, 4, 1, 6, 7, 8, 9}{10, 3, 2, 5, 4, 1, 6, 7, 8, 9}from? His final array is{0, 3, 4, 9, 8, 1, 2, 5, 6, 7}. 0 is the index of 10 in the original array, 3 is the index of 9, 4 is the index of 8, and so on.Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));can fail ifnums[b]is very large andnums[a]is a negative number. Integer overflow will rear its ugly head. See blog.mischel.com/2016/11/21/…