在Java中对匹配的数组进行排序 [英] Sorting matched arrays in Java

查看:74
本文介绍了在Java中对匹配的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数组(在Java中),

Let's say that I have two arrays (in Java),

int []数字;和int [] colors;

int[] numbers; and int[] colors;

数字中的每个第i个元素对应于颜色中的第i个元素。
Ex,numbers = {4,2,1}
colors = {0x11,0x24,0x01};意味着数字4是颜色0x11,数字2是0x24等等。

Each ith element of numbers corresponds to its ith element in colors. Ex, numbers = {4,2,1} colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc.

我想对数字数组进行排序,但是仍然有它,所以每个元素都与它匹配颜色对。

I want to sort the numbers array, but then still have it so each element matches up with its pair in colors.

Ex。数字= {1,2,4};
colors = {0x01,0x24,0x11};

Ex. numbers = {1,2,4}; colors = {0x01,0x24,0x11};

最干净,最简单的方法是什么?阵列有几千个项目,因此最好,但不是必需的。做一个Arrays.sort()和自定义比较器是否有意义?最好尽可能使用库函数。

What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable.

注意:我知道最佳解决方案是为两个元素创建一个类并使用自定义比较。这个问题的目的是要求人们以最快的方式对此进行编码。想象一下参加一个编程竞赛,你不会想要制作所有这些额外的类,比较器的匿名类等等。更好的是,忘记Java;你会如何在C中编码呢?

推荐答案

你可以使用sort()和自定义比较器带索引的第三个数组,并对其进行排序,使数据保持不变。

You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.

Java代码示例:

Integer[] idx = new Integer[numbers.length];
for( int i = 0 ; i < idx.length; i++ ) idx[i] = i;              
Arrays.sort(idx, new Comparator<Integer>() {
    public int compare(Integer i1, Integer i2) {                        
        return Double.compare(numbers[i1], numbers[i2]);
    }                   
});

// numbers[idx[i]] is the sorted number at index i
// colors[idx[i]] is the sorted color at index i

请注意,您必须使用 Integer 而不是 int 或者您不能使用自定义比较器。

Note that you have to use Integer instead of int or you can't use a custom comparator.

这篇关于在Java中对匹配的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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