2015-04-07 157 views
1

排序陣列柱像我想在這裏做的是我的最後一排我的值進行排序,並根據對其他colums是排序數可能在同一行中也改變排序二維數組3列

例如

int[][] array= { {1, 5, 3},{2, 6, 4},{12, 10, 1},{30, 75, 1} };

和輸出應該是

{12, 10, 1} {30, 75, 1} {1, 5, 3} {2, 6, 4}

`System.out.println(「Entre la cantidad de procesos que quiere correr:」); int pros = scan.nextInt();

   int[][] myArr = new int[pros][3]; 

       for(int i=0; i< pros; i++){ 


        System.out.println("CPU Burst proceso "+count+" :"); 
        time2=scan.nextInt(); 

        System.out.println("Arrival Time proceso "+count+" :"); 
         arrt=scan.nextInt(); 


         myArr[i][0]=count; 
         myArr[i][1]=time2; 
         myArr[i][2]=arrt; 


       count++; 
       } 


       Arrays.sort(myArr, new Comparator<int[]>() { 
        public int compare(int[] o1, int[] o2) { 
         return Integer.compare(o2[2], o1[2]); 
        } 
       }); 



       System.out.println(Arrays.deepToString(myArr)); ` 
+5

你能分享你已經嘗試到現在什麼。你至少需要中途到達,以便我們能夠幫助你。 – Panther

+0

我發現,但我試圖實施,但沒有工作\t \t \t \t \t myArr.sort(function(a,b){return a [2] - b [2]; \t}); –

+0

可以請你幫我分類算法,你想要的。根據你的輸入和輸出,我不能排除任何邏輯 –

回答

-1

讓我們構造一個輔助數組,其長度是一樣的array.length

int[] thirdColumnValues = new int[array.length]; 

然後,我們可以複製第三列的值:

for(int i = 0; i < array.length; i++) { 
    thirdColumnValues[i] = array[i][2]; 
} 

然後我們就可以解決這輔助陣列:

Arrays.sort(thirdColumnValues); 

然後我們就可以存儲分類值放回原數組:

for(int i = 0; i < array.length; i++) { 
    array[i][2] = thirdColumnValues[i]; 
} 
+0

bu我的數組是2d並且可以在3列上排序 –

+0

Oops ..誤解了你的問題! –

1

您可以使用自定義Comparator由第三個元素的數組進行比較。

我們可以使用下面的比較:

(a1, a2) -> Integer.compare(a1[2], a2[2]) 

接受兩個數組作爲參數和返回Integer.compare()對他們的第三個要素的結果。

例如:

int[][] array = {{1, 5, 3}, {2, 6, 4}, {12, 10, 1}, {30, 75, 1}}; 
Arrays.sort(array, (a1, a2) -> Integer.compare(a1[2], a2[2])); 
System.out.println(Arrays.deepToString(array)); 

輸出:

[[12, 10, 1], [30, 75, 1], [1, 5, 3], [2, 6, 4]] 
+0

a1或a2是什麼? –

+0

@IfrahimHernandez只是表示我們正在比較的兩個「int []'數組的變量。 –

+0

我從哪裏得到比較器 –