繁体   English   中英

排序后获取数组的索引?

[英]Get the indices of an array after sorting?

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

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

我知道它的长度

index数组将是:

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

现在,在使用Arrays.sort(Array);对其进行Arrays.sort(Array);Arrays.sort(Array);

newArray将类似于:

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

并且newIndex将是:

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

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

提前致谢

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

诚然,这意味着以自定义方式对整数数组进行排序 - 这意味着使用Integer[]和标准 Java 库,或者使用具有“IntComparator”接口的 3rd 方库,该接口可以与sort(int[], IntComparator)类型的方法。

编辑:好的,这是一个示例比较器。 为简单起见,我假设您只想对“原始”字符串数组进行排序……而且我不会费心进行无效性测试。

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.

使用 Java 8 Stream API 实现这一点的简洁方法,

final String[] strArr = {"France", "Spain", "France"};
int[] sortedIndices = IntStream.range(0, strArr.length)
                .boxed().sorted((i, j) -> strArr[i].compareTo(strArr[j]) )
                .mapToInt(ele -> ele).toArray();
TreeMap<String,Int> map = new TreeMap<String,Int>();
for( int i : indexes ) {
    map.put( stringarray[i], i );
}

现在迭代 map.values() 以按排序顺序检索索引,并通过 map.keySet() 获取字符串,或通过 map.entrySet() 获取 String-index-Pairs。

如果有重复排序具有正值的原始 float 或 int 数组的场景,那么与使用任何比较器相比,如下所示的方法会产生更好的 (x3~x4) 速度:

long time = System.currentTimeMillis();
for (int i = 0; i < iters; i++) {           
    float[] array = RandomUtils.randomFloatArray(-1,  1, 3000);
    long[] valueKeyPairs = new long[array.length]; 
    for (int j = 0; j < array.length; ++j) {
        valueKeyPairs[j] = (((long) Float.floatToIntBits(array[j])) << 32) | (j & 0xffffffffL);
    }
    Arrays.sort(valueKeyPairs);
    /**Then use this to retrieve the original value and index*/
    //long l = valueKeyPairs[j];
    //float value = Float.intBitsToFloat((int) (l >> 32));
    //int index = (int) (l);
}
long millis = System.currentTimeMillis() - time;

我根据@Skeet 的代码做了以下内容。 我认为它更像是 OOPie。 我不知道。

public static <T extends Comparable<T>> List<Integer> sortIndex(List<T> in) {
    ArrayList<Integer> index = new ArrayList<>();
    for (int i = 0; i < in.size(); i++) {
        index.add(i);
    }

    Collections.sort(index, new Comparator<Integer>() {
        @Override
        public int compare(Integer idx1, Integer idx2) {
            return in.get(idx1).compareTo(in.get(idx2));
        }
    });

    return index;
}

原始数组中的对象必须实现 Comparable 接口,而不是实现排序和索引的类具有用于不同对象的 Comparator 代码。 似乎许多感兴趣的对象都有自然排序,并且已经实现了 Comparable 接口。

public static void main(String[] args) {

    List<Integer> a1 = new ArrayList<>(Arrays.asList(2, 3, 9, 4, 1));
    // Just pass in the list to have its indexes sorted by the natural ordering
    List<Integer> idx = sortIndex(a1);

    List<Double> a2 = new ArrayList<>(Arrays.asList(1.0, 5.3, 5.2, -3.1, 0.3));
    idx = sortIndex(a2);

    List<numBits> a3 = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        a3.add(new numBits(i));
    }

    // If you need to sort the indexes of your own object, you must implement
    // the Comparable Interface.
    idx = sortIndex(a3);
}

static class numBits implements Comparable<numBits> {
    private int a;

    public numBits(int i) {
        a = i;
    }

    public String toString() {
        return Integer.toString(a);
    }

    // Sort by the total number of bits in the number.
    @Override
    public int compareTo(numBits that) {
        if (Integer.bitCount(this.a) < Integer.bitCount(that.a))
            return -1;
        if (Integer.bitCount(this.a) > Integer.bitCount(that.a))
            return 1;
        return 0;
    }
}

您可以这样做的一种方法是将原始索引和国家/地区名称包装到一个单独的类中。 然后根据名称对 Array 进行排序。 这样,您的原始索引将被保留。

乍一看是这样映射它们

Map <Integer, String> map = new HashMap<Integer, String>();
map.put(0, "France");
map.put(1, "Spain");
map.put(2, "France");

然后按这样的值对它们进行排序,然后您就可以知道它们的索引和值(键、值),只需打印地图

Iterator mapIterator = map.keySet().iterator();  

while (mapIterator .hasNext()) {  
     String key = mapIterator.next().toString();  
     String value = map.get(key).toString();  

     System.out.println(key + " " + value);  
}

我找到了解决方案。

List<String> a = {b, a, d, c};
List<Integer> b = {2, 1, 4, 3};

如果a排序

private void setsortb() {
List<String> beforeA = new ArrayList<>();
List<Integer> beforeB = new ArrayList<>();
beforeA.addAll(a);
beforeB.addAll(b);
a.sort();//change like this {a, b, c, d}

for(int i = 0; i < beforeA.size(); i++) {
int index = beforeA.indexOf(a.get(i));
b.set(i, beforeB.get(i));
}
}

像这样

结果

a = {a, b, c, d}
b = {1, 2, 3, 4}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM