繁体   English   中英

根据另一个数组的值对一个数组排序

[英]Sorting an array based on the values of another array

我想对一个数组进行排序,问题是该数组的每个元素在另一个数组中都有特定的值,例如第一个array = {31,12,88,74,55}第二个数组= {5,2,3,3, 5}在对第二数组元素进行降序排序时,必须交换第一数组中的相应值。 第一个数组= {31,55,74,88,12}第二个数组= {5,5,3,3,2}

听起来好像您要存储一个对象数组,其中每个对象都有两个值。

public class X implements Comparable<X> {
    private int a;
    private int b;

    public X(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public int compareTo(X other) {
        return a - other.a;
    }
}

然后,您可以列出这些项目并对其进行排序。

List<X> items = ... // Fill in the blanks
Collections.sort(items);

您只需编写两个for循环即可对第二个数组进行排序,并同时对第一个数组进行相同的更改。

for (int i = 0; i < array2.length; i++){
    for (int j = 0; j < array2.length; j++){
        if (array2[i] < array2[j] && i < j){
            int temp1 = array1[i];
            int temp2 = array2[i];

            array1[i] = array1[j];
            array2[i] = array2[j];

            array1[j] = temp1;
            array2[j] = temp2;
        }
    }
}

在对第二个数组进行排序时,第一个数组的元素将以完全相同的方式移动,而不管它们的值如何。

希望这可以帮助!

暂无
暂无

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

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