Java冒泡排序

public class Sort {

  public static void main(String[] args) {

    //首先定义一个数组(长度为n)
    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) + "}");
  }
}

posted @ 2018-01-17 20:23  跳跳糖~  阅读(203)  评论(0编辑  收藏  举报