就是對二維數組做一個對角線調換資料
效果:
* 轉換之前:
* a[0][0]=1 a[0][1]=2 a[0][2]=3
* a[1][0]=4 a[1][1]=5 a[1][2]=6
* a[2][0]=7 a[2][1]=8 a[2][2]=9
* 轉換之後:
* a[0][0]=9 a[0][1]=2 a[0][2]=7
* a[1][0]=4 a[1][1]=5 a[1][2]=6
* a[2][0]=3 a[2][1]=8 a[2][2]=1
代碼部分:
public static void main(String[] args) {
//初始化資料 并輸出 既然要進行對角線轉換 行和列就要一樣 不然也沒有了對角線的意義
int a[][] = getArray(4);
changeArray(a);
}
//初始化資料 并輸出
public static int[][] getArray(int num){
//構造資料
int [][] a = new int[num][num] ;
int flag = 1;
for(int i=0; i<num; i++){
for(int j=0; j<num; j++){
a[i][j] = flag;
flag++;
}
}
//初始資料輸出
System.out.println("原始資料輸出...");
outArray(a);
return a;
}
//對角線對稱變換并輸出
public static void changeArray(int [][] a){
if(a != null)
{
//擷取數組的行
int row = a.length; //數組下标從0開始
//範圍内據行數确定需要進行轉換的行 奇數行中間的一個不需要轉換 偶數上面一半資料和下面一半進行調換就行了
int changeRow = row%2 == 0 ? row/2 : (int)Math.floor(row*1.0/2);
row--; //數組下标從0開始對row減一
for(int i=0; i<changeRow; i++)
{
//數組左對角線資料調換
int temp = a[i][i];
a[i][i] = a[row-i][row-i];
a[row-i][row-i] = temp;
//右對角線資料調換
temp = a[i][row-i];
a[i][row-i] = a[row-i][i];
a[row-i][i] = temp;
}
}
else
{
System.out.println("數組為空!");
}
System.out.println("排序後資料輸出");
//資料輸出
outArray(a);
}
public static void outArray(int[][] a){
for(int i=0; i<a.length ;i++){
for(int j=0; j<a[i].length ;j++){
System.out.print("\ta["+i+"]["+j+"]=" + a[i][j]);
}
System.out.println();
}
}