По сути, вы ищете перестановку массива.В частности, для перестановки сортировки.
К сожалению, обозначения несколько двусмысленны и запутаны при обращении к индексам.Основное различие заключается в том, должен ли
sorted[indices[i]] = array[i]
или
sorted[i] = array[indices[i]]
давать отсортированный массив.По вашему вопросу вы ищете последнее.
Это может быть реализовано различными способами, либо путем помещения элементов в List<Integer>
и сортировки этого списка с использованием компаратора, который ссылается на исходный массив, либо путем сортировки списка «пар», каждая из которых состоит изстоимости и ее исходного индекса.(Этот подход был в основном уже показан tdelev в его ответе )
Вот реализация, которая явно вычисляет индексный массив и применяет его как перестановку к входному массиву:
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.IntBinaryOperator;
public class SortingPermutations
{
public static void main(String[] args)
{
int[] a = {6,10,16,11,7,12,3,9,8,5} ;
int[] p = computeAscendingSortingPermutation(a);
int[] s = applyPermutation(a, p);
System.out.println("array : " + Arrays.toString(a));
System.out.println("permutation : " + Arrays.toString(p));
System.out.println("sorted : " + Arrays.toString(s));
}
/**
* Compute the sorting permutation for the given array. This will return
* an array <code>p</code> so that <code>sorted[i] = array[p[i]]</code>
* will result in an array where the values are sorted in ascending order.
*
* @param array The array
* @return The sorting permutation
*/
private static int[] computeAscendingSortingPermutation(int array[])
{
return computeSortingPermutation(array, Integer::compare);
}
/**
* Compute the sorting permutation for the given array. This will return
* an array <code>p</code> so that <code>sorted[i] = array[p[i]]</code>
* will result in an array where the values are sorted according to
* the given comparator
*
* @param array The array
* @param intComparator The comparator for the integer values
* @return The sorting permutation
*/
private static int[] computeSortingPermutation(
int array[], IntBinaryOperator intComparator)
{
class Entry
{
int value;
int index;
}
int n = array.length;
Entry entries[] = new Entry[n];
for (int i = 0; i < n; i++)
{
Entry e = new Entry();
e.value = array[i];
e.index = i;
entries[i] = e;
}
Comparator<Entry> comparator =
(e0, e1) -> intComparator.applyAsInt(e0.value, e1.value);
Arrays.sort(entries, comparator);
int result[] = new int[n];
for (int i = 0; i < n; i++)
{
Entry e = entries[i];
result[i] = e.index;
}
return result;
}
/**
* Apply the given permutation to the given array, and return the result
* as a new array. The result will be an array <code>r</code> where
* <code>r[i] = array[permutation[i]]</code>
*
* @param array The input array
* @param permutation The permutation
* @return The result array
*/
private static int[] applyPermutation(int array[], int permutation[])
{
int n = array.length;
int result[] = new int[n];
for (int i=0; i<n; i++)
{
result[i] = array[permutation[i]];
}
return result;
}
}
Выход
array : [6, 10, 16, 11, 7, 12, 3, 9, 8, 5]
permutation : [6, 9, 0, 4, 8, 7, 1, 3, 5, 2]
sorted : [3, 5, 6, 7, 8, 9, 10, 11, 12, 16]
, как и ожидалось.