简体   繁体   English

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

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

I want to sort an array, the problem is that each element of the array has certain values in another array for example first array={31,12,88,74,55} Second array={5,2,3,3,5} On sorting the second array elements in descending order the corresponding values in the first array has to be interchanged. 我想对一个数组进行排序,问题是该数组的每个元素在另一个数组中都有特定的值,例如第一个array = {31,12,88,74,55}第二个数组= {5,2,3,3, 5}在对第二数组元素进行降序排序时,必须交换第一数组中的相应值。 First array={31,55,74,88,12} Second array={5,5,3,3,2} 第一个数组= {31,55,74,88,12}第二个数组= {5,5,3,3,2}

Sounds like you short be storing an array of objects, where each object has two values. 听起来好像您要存储一个对象数组,其中每个对象都有两个值。

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;
    }
}

Then you can make a list of these items, and sort them. 然后,您可以列出这些项目并对其进行排序。

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

You can simply write two for loops to sort the second array, and make the same changes to the first array at the same time. 您只需编写两个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;
        }
    }
}

While the second array is being sorted, the first array's elements are being moved the exact same way, regardless of their values. 在对第二个数组进行排序时,第一个数组的元素将以完全相同的方式移动,而不管它们的值如何。

Hope this helps! 希望这可以帮助!

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

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