• 冒泡排序法


      直接上代码

      初次版本

    public static void main(String[] args) {
        int[] ints = {1, 5, 2, 6, 8, 4};
        for (int i = 0; i < ints.length; i++) {
          for (int j = 0; j < ints.length - i - 1; j++) {
            if (ints[j] > ints[j + 1]) {
              int temp = ints[j];
              ints[j] = ints[j + 1];
              ints[j + 1] = temp;
            }
          }
        }
        System.out.println(Arrays.toString(ints));
      }
    View Code

    优化版本

    public static void main(String[] args) {
        int[] ints = {11, 5, 2, 6, 8, 4};
        for (int i = 0; i < ints.length; i++) {
          Boolean swap = true;
          for (int j = 0; j < ints.length - i - 1; j++) {
            if (ints[j] > ints[j + 1]) {
              int temp = ints[j];
              ints[j] = ints[j + 1];
              ints[j + 1] = temp;
              swap = false;
            }
          }
          if (swap) {
            break;
          }
        }
        System.out.println(Arrays.toString(ints));
      }
    View Code

    优化思想是:

      如果发现一次比较中没有发生排序现象则判断是有序数组了。

  • 相关阅读:
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11729791.html
Copyright © 2020-2023  润新知