如何按索引对数组进行排序?(SortIndex)

SAb*_*deh 3 java arrays

我有long[]它的价值观.我需要的是有一个排序数组,其中包含我的第一个数组的索引.

例如:

INPUT:

long[ ] values = {1 , 3 , 2 , 5 , 4};
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

long[ ] SortIndex = {0 , 2 , 1 , 4 , 3}
Run Code Online (Sandbox Code Playgroud)

意思是:

values[0] < values[2] < values[1] < values[4] < values[3] 
Run Code Online (Sandbox Code Playgroud)

......降序或升序SortIndex并不重要.

aro*_*oth 5

long[] values = {1 , 3 , 2 , 5 , 4};
Map<Long, Integer> indices = new HashMap<Long, Integer>();
for (int index = 0; index < values.length; index++) {
    indices.put(values[index], index);
}

long[] copy = Arrays.copyOf(values, values.length);
Arrays.sort(copy);
for (int index = 0; index < copy.length; index++) {
    copy[index] = indices.get(copy[index]);
}
Run Code Online (Sandbox Code Playgroud)

你的指数列表将在copy.

这里的工作示例:http: //ideone.com/A9Imz

  • 当你的价值观是独一无二的时候,这是真的,我没有提到任何这样的约束. (4认同)