[英]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.