排序后获取数组的索引? [英] Get the indices of an array after sorting?

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

问题描述

假设用户输入一个数组,例如:

Suppose the user enter an array, for example:

Array = {France, Spain, France, France, Italy, Spain, Spain, Italy}

我知道它的长度

索引数组将是:

index = {0, 1, 2, 3, 4, 5, 6, 7}

现在,在使用 Arrays.sort(Array)排序之后;

newArray 将如下:

newArray = {France, France, France, Italy, Italy, Spain, Spain, Spain}

newIndex 将是:

newIndex = {0, 2, 3, 4, 7, 1, 5, 6}

问题是:如何从输入数组中找到 newIndex

The problem is: how can I find the newIndex from the input Array?

提前致谢

推荐答案

不要对数组进行排序以启动用。对索引数组进行排序,传入一个比较器,该比较器将值作为索引比较到数组中。因此,您最终得到 newIndex 作为排序的结果,从那里到实际项目的排序数组是微不足道的。

Don't sort the array to start with. Sort the index array, passing in a comparator which compares values by using them as indexes into the array. So you end up with newIndex as the result of the sort, and it's trivial to go from there to the sorted array of actual items.

不可否认,这意味着以自定义方式对整数数组进行排序 - 这意味着使用 Integer [] 和标准Java库,或第三方具有IntComparator接口的库,可以与 sort(int [],IntComparator)类型的方法一起使用。

Admittedly that means sorting an array of integers in a custom way - which either means using an Integer[] and the standard Java library, or a 3rd party library which has an "IntComparator" interface which can be used in conjunction with a sort(int[], IntComparator) type of method.

编辑:好的,这是一个示例比较器。为了简单起见,我假设你只想对一个原始字符串数组进行排序......我不打算进行无效测试。

Okay, here's an example comparator. For the sake of simplicity I'll assume you only want to sort an "original" array of strings... and I won't bother with nullity testing.

public class ArrayIndexComparator implements Comparator<Integer>
{
    private final String[] array;

    public ArrayIndexComparator(String[] array)
    {
        this.array = array;
    }

    public Integer[] createIndexArray()
    {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++)
        {
            indexes[i] = i; // Autoboxing
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2)
    {
         // Autounbox from Integer to int to use as array indexes
        return array[index1].compareTo(array[index2]);
    }
}

您可以这样使用它:

String[] countries = { "France", "Spain", ... };
ArrayIndexComparator comparator = new ArrayIndexComparator(countries);
Integer[] indexes = comparator.createIndexArray();
Arrays.sort(indexes, comparator);
// Now the indexes are in appropriate order.

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

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