如何排序的索引的数组? (SortIndex) [英] How to sort an array by its index? (SortIndex)

查看:121
本文介绍了如何排序的索引的数组? (SortIndex)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a long[] with its values. The thing I need is to have a sorted array that contains the indices of my first array.

例如:

输入:

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

OUTPUT:

OUTPUT:

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

这意味着:

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

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

推荐答案

我是使用java 比较接口发现了另一个优雅的解决方案。它也可以当这些值不是唯一的:

I found another elegant solution by using the java Comparator interface. It also works when the values are not unique:

final Long[] values = { 1, 3, 2, 5, 4, 2};
Integer[] indices = new Integer[values.length];
for (int i = 0; i < indices.length; i++) {
    indices[i] = i;
}
Comparator<Integer> comparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer arg0, Integer arg1) {
        return values[arg0].compareTo(values[arg1]);
    }
};
Arrays.sort(indices, comparator);
System.out.println(Arrays.toString(indices));

OUTPUT:

OUTPUT:

[0, 2, 5, 1, 4, 3]


  • 您可以将输出顺序从升序通过改变比较降序排列修改比较()方法:

    public int compare(Integer arg0, Integer arg1) {
        return values[arg1].compareTo(values[arg0]);
    }
    


  • 您还可以修改龙[] 与其他任何可比的数据类型。

  • You can also change the Long[] with any other comparable data type.

    这篇关于如何排序的索引的数组? (SortIndex)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆