你的位置:首页 > Java教程

[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();
  }

}