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

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

问题描述

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

Suppose the user enter an array, for example:

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

我确实知道它的长度

index 数组将是:

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"接口的第 3 方库可以与 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天全站免登陆