package com.hylink;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @function 给String型二维数组的一维排序
* @author ylchou@qq.com
* @date 2013-07-07
*/
class Sort {
public static void main(String[] args) {
String[][] arr = new String[][] { { "活动", "媒体", "广告位2", "6" }, { "活动", "媒体", "广告位2", "1"},
{ "活动", "媒体", "广告位2", "9"}, { "活动", "媒体", "广告位2", "5"},
{ "活动", "媒体", "广告位1", "9"}, { "活动", "媒体", "广告位1", "5"}
, { "活动", "媒体", "广告位2", "5"}};
List<String> list = new ArrayList<String>();
System.out.println("排序前的二维数组(此处为了方便,打印的是二维数组转化为String输出的):");
//把二维数组转换为一维数组(一维元素含"\t"),然后加入到list
for (int i = 0; i < arr.length; i++) {
StringBuffer line = new StringBuffer();
for (int j = 0; j < arr[i].length; j++) {
if(j<arr[i].length-1){
line.append(arr[i][j]+"\t");
}else if(j==arr[i].length-1){
line.append(arr[i][j]);
}
}
list.add(line.toString());
System.out.println(line.toString());
}
//排序
Collections.sort(list);
//把list转换为二维数组
for (int i = 0; i < list.size(); i++) {
String[] strSplit = list.get(i).toString().split("\t");
for (int j = 0; j <strSplit.length; j++) {
arr[i][j] = String.valueOf(strSplit[j]);
}
}
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:
排序前的二维数组(此处为了方便,打印的是二维数组转化为String输出的):
活动 媒体 广告位2 6
活动 媒体 广告位2 1
活动 媒体 广告位2 9
活动 媒体 广告位2 5
活动 媒体 广告位1 9
活动 媒体 广告位1 5
活动 媒体 广告位2 5
------------------华丽的分割线-----------------------
排序后的二维数组:
活动 媒体 广告位1 5
活动 媒体 广告位1 9
活动 媒体 广告位2 1
活动 媒体 广告位2 5
活动 媒体 广告位2 5
活动 媒体 广告位2 6
活动 媒体 广告位2 9
PS:这里我也是把String类型的数组也是用JDK自带的工具类 Collections的sort()方法来排序的。用九大排序法能否实现之呢?