欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java冒泡排序

程序员文章站 2022-06-27 19:35:42
public class Sort { public static void main(String[] args) { //首先定义一个数组 int[] arrs = { 7, 2, 1, 6, 5, 3, 9, 0 }; String s1 = ""; for (int i : arrs) { ......

public class Sort {

  public static void main(String[] args) {

    //首先定义一个数组
    int[] arrs = { 7, 2, 1, 6, 5, 3, 9, 0 };

    String s1 = "";
    for (int i : arrs) {
      s1 += i + ",";
    }
    System.out.println("排序前:{" + s1.substring(0, s1.length() - 1) + "}");

    // 最多做n - 1趟排序
    for (int i = 0; i < arrs.length - 1; i++) {
      // 对当前无序的区间进行排序
      // arrs[0,1,...,arrs.length - i - 1]
      for (int j = 0; j < arrs.length - i - 1; j++) {
        if (arrs[j] > arrs[j + 1]) {
          int temp = arrs[j];
          arrs[j] = arrs[j + 1];
          arrs[j + 1] = temp;
        }
      }
    }
    String s2 = "";
    for (int i : arrs) {
      s2 += i + ",";
    }
    System.out.println("排序后:{" + s2.substring(0, s2.length() - 1) + "}");
  }
}