日期:2014-05-20 浏览次数:20782 次
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Example8_4 { public static void main(String args[]) { int [][]ss=new int[][]{{23,4,56},{3,12,78,9},{1,21}}; List<Integer> list = new ArrayList<Integer>(); for(int i=0;i<ss.length;i++){ for(int j=0;j<ss[i].length;j++){ list.add(ss[i][j]); } } Collections.sort(list); System.out.println(list); int index = 0; for(int i=0;i<ss.length;i++){ for(int j=0;j<ss[i].length;j++){ ss[i][j] = list.get(index++); } } for(int i=0;i<ss.length;i++){ System.out.print(Arrays.toString(ss[i])); } } }
------解决方案--------------------
正解!
个人技术博客 http://www.happyalaric.com/
int [][]ss=new int[][]{{23,4,56},{3,12,78,9},{1,21}}; int count = 0, flag = 0; while (true) { for (int i=0; i<ss.length; i++) { for (int j=0; j<ss[i].length; j++) { if (j+1 < ss[i].length) { //如果当前列没到达最后,则直接比较 if (ss[i][j] > ss[i][j+1]) { //比较当前元素和下一个元素 int tmp = ss[i][j]; ss[i][j] = ss[i][j+1]; ss[i][j+1] = tmp; } } else if (i+1 < ss.length) {//如果当前列到达最后,则换行 if (ss[i][j] > ss[i+1][0]) { //比较当前元素和下一个元素 int tmp = ss[i][j]; ss[i][j] = ss[i+1][0]; ss[i+1][0] = tmp; } } if (flag == 0) count++; else flag++; if (flag == count) break; } } flag = 1; count--; if (count == 1) break; } for (int i=0; i<ss.length; i++) { for (int j=0; j<ss[i].length; j++) { System.out.printf("%d ", ss[i][j]); } System.out.println(); }