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

标签 java arrays

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

例如:

输入:

long[ ] values = {1 , 3 , 2 , 5 , 4};

输出:

long[ ] SortIndex = {0 , 2 , 1 , 4 , 3}

这意味着:

values[0] < values[2] < values[1] < values[4] < values[3] 

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

最佳答案

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]);
}

您的索引列表将在 copy 中。

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

关于java - 如何按索引对数组进行排序? (排序索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8286982/

相关文章:

Java(匿名与否)内部类 : is it good to use them?

java - 如何在android studio中获取JSON对象的字段?

java - 如何将并行进程同步到 Web 服务中?

python - 如果它出现在纯 numpy 中的另一个数组中,则有效地删除数组的每一行

java - 所有类中都有变量,但仅在运行时才有值(value)

python - 将 Array_list 值插入另一个空 Array_list

c++ - 将值从 Map 复制到 C++ 程序中的 256x256 数组

c - 使用 realloc 连接字符串

php - 我可以在类变量中添加没有赋值的 PHP 数组键吗?

java - 这个错误是什么意思以及我的代码有什么问题?