当前位置:   article > 正文

java中二维数组排序

java中二维数组排序
package practice;
import java.util.Scanner;
public class Paixu{
 static void sort2(int n,int m){
 System.out.println("随机产生的"+n+"行"+m+"列数组:");
 int [][] a = new int[n][m];
 for (int i = 0;i < a.length; i++) {
  for (int j = 0;j < a[i].length; j++) {
   a[i][j] = (int)(Math.random()*110)-10;


  }
 }
 for (int i = 0;i < a.length; i++) {
  for (int j = 0;j < a[i].length; j++) {
   System.out.print(a[i][j]);
   System.out.print("\t");
  }
  System.out.println();
 }
 for (int k = 0;k < n*m; k++) {
  for (int i = 0;i < n; i++) {
   for (int j = 0;j < m; j++) {
    if ((j+1)%a[i].length != 0) {
     if (a[i][j] > a[i][j+1]) {
      int temp = a[i][j];
      a[i][j] = a[i][j+1];
      a[i][j+1] = temp;
     }
    } else {
     if (i+1 != a.length) {
      if (a[i][j] > a[i+1][(j+1)%a[i].length]) {
       int temp = a[i][j];
       a[i][j] = a[i+1][(j+1)%a[i].length];
       a[i+1][(j+1)%a[i].length] = temp;
      }
     }
    }
   }
  }
 }
 System.out.println("排序后");
 for (int i = 0;i < a.length; i++) {
  for (int j = 0;j < a[i].length; j++) {
   System.out.print(a[i][j]);
   System.out.print("\t");
  }
  System.out.println();
 } 
}
public static void main(String[] args) {
System.out.println("please input n and m:");
Scanner scan = new Scanner(System.in);
try{
int a=scan.nextInt();
int b=scan.nextInt();
sort2(a,b);
}catch(Exception e){
System.out.println("捕获到异常,异常信息是"+e.getMessage());
}
}
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/995528
推荐阅读
相关标签
  

闽ICP备14008679号