Posted on 2007-10-19 10:28
久城 閱讀(4384)
評論(1) 編輯 收藏 所屬分類:
JavaTest
早上來公司的路上,路邊一片綠油油的小草上都披上了一身白霜。樹葉突然間變黃了,我終于完全的感覺到了,秋的氣息。
參照:http://www.tkk7.com/realsmy/archive/2007/10/17/153435.html,繼續(xù)這個問題,用JAVA實現(xiàn)對二維數(shù)組的排序。順便學(xué)習(xí)了一下Comparable接口。

/** *//**
* Class Name : YW2_Test02.java
* Purpose : 對二維數(shù)組按列排序
*
* @author realsmy
* @since 2007/10/19
*
* Copyright realsmy. All rights reserved.
*/
package com.neusoft.test;

import java.util.*;


public class YW5_Test02
{
private int ary[][];
private MySort mySort;
// 數(shù)據(jù)初始化

public YW5_Test02(int ary[][], MySort mySort)
{
this.ary = ary;
this.mySort = mySort;
}
// 排序

public void sort()
{
Arrays.sort(ary, mySort);
printArray();
}
// 打印

private void printArray()
{
System.out.println("---------Begin---------");

for (int[] a : ary)
{
for (int i : a)
System.out.print(i + " ");
System.out.println();
}
System.out.println("---------End---------");
}

public static void main(String[] arg) throws Exception
{
//int ary[][] = { {1,5,456,6,89}, {2,51,515,32,15}, {3,45,68,24,6}, {4,822,4,88,462}, {5,87,44,865,99}};
int ary[][] = RandomArray.GetArray(4, 5);
new YW5_Test02(ary, new MySort(0,"asc")).sort();
new YW5_Test02(ary, new MySort(1,"asc")).sort();
new YW5_Test02(ary, new MySort(2,"desc")).sort();
new YW5_Test02(ary, new MySort(3,"asc")).sort();
new YW5_Test02(ary, new MySort(4,"desc")).sort();

}
}


class MySort implements Comparator<int[]>
{
// 想要進(jìn)行排序的列數(shù)
private int columnNumber;
// 排序方式:desc or asc
private String order;


public MySort(int columnNumber, String order)
{
this.columnNumber = columnNumber;
this.order = order;
}


public int compare(int a[], int b[])
{

if ("desc".equals(order))
{
return b[columnNumber] - a[columnNumber];

} else
{
return a[columnNumber] - b[columnNumber];
}

}
}


class RandomArray
{
// 隨機(jī)生成二維數(shù)組

public static int[][] GetArray(int row, int column)
{
Random random = new Random();
int i, j;
int[][] array;
if ((row > 0) && (column > 0))
array = new int[row][column];
else
array = new int[1][1];
for (i = 0; i < array.length; i++)

for (j = 0; j < array[i].length; j++)
{
array[i][j] = random.nextInt(100);
}
return array;
}
}
Comparable接口第一次接觸,感覺很好。
歡迎來訪!^.^!
本BLOG僅用于個人學(xué)習(xí)交流!
目的在于記錄個人成長.
所有文字均屬于個人理解.
如有錯誤,望多多指教!不勝感激!