2012-09-04 179 views
0

我完全不知道如何去解決這個問題,但是我在Java中使用了一個用於AI Pathfinder系統的數組,並且我需要對這些值進行排序。下面是我生成的陣:Java多維數組排序

int[][] paths = new int[Settings.GAME_COLS][Settings.GAME_ROWS]; // Just creating an Array that has room for every tile in the Game, so the Array can be used like this: paths[x][y] 
int tempF = 0; 

tempF = Math.abs(14 + (((aiX + 1) - playerX) + ((aiY - 1) - playerY))); 
paths[aiX + 1][aiY - 1] = tempF; 
tempF = Math.abs(14 + (((aiX + 1) - playerX) + ((aiY + 1) - playerY))); 
paths[aiX + 1][aiY + 1] = tempF; 
tempF = Math.abs(14 + (((aiX - 1) - playerX) + ((aiY + 1) - playerY))); 
paths[aiX - 1][aiY + 1] = tempF; 
tempF = Math.abs(14 + (((aiX - 1) - playerX) + ((aiY - 1) - playerY))); 
paths[aiX - 1][aiY - 1] = tempF; 
tempF = Math.abs(10 + (((aiX + 1) - playerX) + (aiY - playerY))); 
paths[aiX + 1][aiY ] = tempF; 
tempF = Math.abs(10 + (((aiX - 1) - playerX) + (aiY - playerY))); 
paths[aiX - 1][aiY ] = tempF; 
tempF = Math.abs(10 + ((aiX - playerX) + ((aiY + 1) - playerY))); 
paths[aiX ][aiY + 1] = tempF; 
tempF = Math.abs(10 + ((aiX - playerX) + ((aiY - 1) - playerY))); 
paths[aiX ][aiY - 1] = tempF; 

的所有作品,完美地找到並生成所需要的信息的陣列,但我需要根據到陣列添加了「tempF」數值數組進行排序。是否有捷徑可尋?

+0

我把二維排序你可以試試嗎?請,並可以告訴我結果? –

回答

2

多維數組不過是一組數組,所以你可以使用常規的方法,它會就地排列你的數組數組。

+0

我已經嘗試過 - 我只是得到很多控制檯錯誤。線程中的異常「AWT-EventQueue-0」java.lang.ClassCastException:[我不能轉換爲java.lang.Comparable' – Oyed

+0

請分享一些代碼 – jdevelop

+0

這就是我正在使用的'Arrays.sort(paths) ;' – Oyed

0
for(int k=0;k<N;k++) // loop for relaxation between row-column sorts 
{ 
    for(int i=0;i<N;i++) 
    { 
     //row-wise sortings(for all rows) 
     Arrays.sort(your_array[i]); 
    } 

     for (int c = 0 ; c < N ; c++) 
     { 
     for(int d = 0 ; d < N ; d++)    
     transposed_your_array[d][c] = your_array[c][d];   
     } 

    for(int i=0;i<N;i++) 
    { 
     //column-wise sortings(for all columns) 
     Arrays.sort(transposed_your_array[i]); 
    } 

    for (int c = 0 ; c < N ; c++) 
    { 
     for(int d = 0 ; d < N ; d++)    
     your_array[d][c] = transposed_your_array[c][d];   
    } //getting original array from transpose 


} 
//There are actually N*N 1-D(N-element)arrays in a N x N matrix 
//Every sort on a row-array alters the bounding column-arrays too(N of them) 


//a worked example: 
//8 3 8 
//11 8 3 
//6 12 6 

//output: 
// this(0,0) is smallest element 
//^
// | 
// 3 6 8 
// 3 8 11 
// 6 8 12 ---->this (2,2) is biggest element 

//some other examples: 
//10 8 8 
//11 4 7 
//9 5 3 
// 
//3 5 9 ----> this 9 could be in place of 8 down there but this 
//4 7 10  program sorts rows first then sorts columns 
//8 8 11  you can interleave them for better resolution sort(slower)