package com.hylink;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @function int型二维数组所有元素排序
* @author ylchou@qq.com
* @date 2013-07-07
*/
public class SortInt {
public static void main(String[] args) {
int arr[][] = new int[][] { { 12, 3, 14, 11 }, { 1, 2, 6, 4 },
{ 5, 15, 7, 8 }, { 1, 2, 6, 4 }, { 5, 9, 10, 13 } };
int a = 0;
List<Integer> list = new ArrayList<Integer>();
System.out.println("排序前的二维数组:");
//把二维数组赋值给list
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (j < arr[i].length - 1) {
System.out.print(arr[i][j] + "\t");
} else if (j == arr[i].length - 1) {
System.out.print(arr[i][j]);
}
list.add(arr[i][j]);
}
System.out.println();
}
//对list排序
Collections.sort(list);
//把list转换为二维数组
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
//注意:此处不能用i或j来代替a,因为a是数组中元素的总个数
arr[i][j] = Integer.parseInt(list.get(a).toString());
a++;
}
}
System.out.println("------------------华丽的分割线-----------------------");
System.out.println("排序后的二维数组:");
//打印转换后的数组元素
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
if (j < arr[i].length - 1) {
System.out.print(arr[i][j] + "\t");
} else if (j == arr[i].length - 1) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
}
console print:
排序前的二维数组:
12 3 14 11
1 2 6 4
5 15 7 8
1 2 6 4
5 9 10 13
------------------华丽的分割线-----------------------
排序后的二维数组:
1 1 2 2
3 4 4 5
5 6 6 7
8 9 10 11
12 13 14 15
PS:此处是用JDK自带的Collections工具类的sort()方法来排序的,当然还可以用冒泡、快速等9大排序方法来排序。