I have an exercise that asks: "Given an array, get a new one ordered descending (from highest to lowest), but through its indices"; that is, if I have the array [2, 5, 1]
, the function should return an array with the values [1, 0, 2]
. That would correspond to the order in which I must access the indexes of the first array to do it in descending order.
The idea that has occurred to me is to order a copy of the array and store the index that I have ordered in a new array, which will be the one returned, but it does not work. I've tried several other things, but I don't quite understand how it could be done.
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
final int[] nums = {8, 7, 1, 8};
final int[] sortedIndexes = seleccion(nums);
System.out.println(Arrays.toString(sortedIndexes));
}
public static int[] seleccion(int[] v) {
final int[] array = Arrays.copyOf(v, v.length);
final int[] sortedIndexes = new int[v.length];
Arrays.fill(sortedIndexes, v.length - 1);
int n = v.length;
int posmax;
for (int i = 0; i < n - 1; i++) {
posmax = i;
for (int j = i + 1; j < n; j++) {
if (array[j] > array[posmax]) {
posmax = j;
}
}
permuta(array, sortedIndexes, i, posmax);
}
return sortedIndexes;
}
public static void permuta(int[] array, int[] arrayIndex, int index, int posmax) {
final int tempValue = array[index];
array[index] = array[posmax];
array[posmax] = tempValue;
arrayIndex[posmax] = index;
}
}
The biggest problem with doing the exercise is that I can't use anything other than loops, conditionals, or arrays.