I have an int array as [2,4,1,0,0,3] and need to obtain from that an array of the indexes in ascending order, means [3,4,2,0,5,1].
I tried to resolve this by using a sorted array to get the numbers in order, then iterating over the original array to find the index when a match happens. As follows:
public class IndexAscendingSorter {
public static void main (String[] args) {
int[] array = {2,4,1,0,0,3};
IndexAscendingSorter finder = new IndexAscendingSorter();
int[] indixes = finder.orderIndexAscending(array);
System.out.println("Indexes of the array in ascending order: " +
Arrays.toString(indixes));
}
public int[] orderIndexAscending(int[] array) {
int[] minimumIndexes = new int[array.length];
int[] sortedArray = array.clone();
Arrays.sort(sortedArray);
for (int index = 0; index < array.length; index++){
int minIndex = 0;
for (int number : array) {
if (number == sortedArray[index]) {
minimumIndexes[index] = minIndex;
break;
}
minIndex++;
}
}
return minimumIndexes;
}
}
The problem is that for same numbers don't return the correct indexes, the output of executing that code is:
Indexes of the array in ascending order: [3, 3, 2, 0, 5, 1] The second value array[1] should have been 4 instead of 3. Does anyone know how can I improve this?