2016-02-11 69 views
0

我想排序一個數組,問題是數組中的每個元素在另一個數組中具有某些值,例如 first array = {31,12,88,74, 55}第二個數組= {5,2,3,3,5} 按降序對第二個數組元素進行排序時,第一個數組中的相應值必須互換。 第一個數組= {31,55,74,88,12}第二個數組= {5,5,3,3,2}基於另一個數組的值排序

+1

爲什麼不使用HashMap?您可以將第一個數組的元素保留爲鍵,將第二個數組的值保留爲其值。排序一個將保持第二個的關聯性 – Sachin

回答

3

聽起來像是你短暫地存儲一個對象數組,其中每個對象都有兩個值。

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); 
1

你可以簡單地寫兩個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; 
     } 
    } 
} 

雖然第二陣列被排序,所述第一陣列中的元素被移動的準確相同的方式,而不管它們的值。

希望這會有所幫助!

相關問題