星空网 > 软件开发 > Java

数组排序(冒泡法)

思路:定义了三个方法分别是sort、swap、printAry,分别执行排序、数组倒置、打印数组的功能,定义倒置数组的目的呢,就是按照用户的需要来打印出是升序还是降序的结果。

CODE:


import java.util.Scanner;

public class ArySort {

/**
* @param args
*/
//排序(降序)
  public static int[] sort(int[] ary){
    for (int i = 1; i < ary.length; i++) {
      for (int j = 0; j < ary.length-i; j++) {
        if(ary[j] < ary[j+1]){
          int temp = ary[j];
          ary[j] = ary[j+1];
          ary[j+1] = temp;
          }
        }
      }
       return ary;
   }

// 数组倒置
  public static int[] swap(int[] ary){
    for (int i = 0,j = ary.length-1; i < ary.length/2; i++,j--) {
      int temp = ary[i];
      ary[i] = ary[j];
      ary[j] = temp;
     }
  return ary;
  }
// 打印数组
  public static void printAry(int[] ary){
    for (int i = 0; i < ary.length; i++) {
      System.out.print(ary[i]+"\t");
     }
   }
  public static void main(String[] args) {
    Scanner ss = new Scanner(System.in);
    System.out.print("请输入数组长度:");
    int len = ss.nextInt();
     if(len < 0){
      System.out.println("数组长度有误!");
      return;
    }
    int[] ary = new int[len];
    for(int i = 0; i < ary.length;i++){
      System.out.println("请输入第"+(i+1)+"数据:");
      ary[i] = ss.nextInt();
    }
    System.out.println("排序前的数组为:");
    printAry(ary);
    sort(ary);
    System.out.println();
    System.out.println("1.升序, 2.降序");
    int a = ss.nextInt();
    if(a == 1){
      swap(ary);
    }
    System.out.println("排序后的数组为:");
    printAry(ary);
    System.out.println();
  }

}




原标题:数组排序(冒泡法)

关键词:排序

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流