排序算法 — 冒泡排序

package com.java.base.sort.algorithm;

/**
 * 冒泡排序
 *
 * <p>算法思路:
 *
 * <p>1.从数列第一个数开始,比较每相邻的两个数, 将较大(或较小)数交换至后面,直到将最大的数交换到数列最后
 *
 * <p>2.再循环第一步直到数列中只剩下第一个数
 *
 * 算法复杂度:O(n²)
 * 稳定性:稳定
 *
 * @author lxy
 */
public class BubbleSort {

  /**
   * 交换
   */
  private static void swap(int[] array, int m, int n) {
    int tmp = array[m];
    array[m] = array[n];
    array[n] = tmp;
  }

  /**
   * 冒泡排序:9,8,11,17,12,2,4,5,20,3,1
   */
  public static int[] bubbleSort(int[] array) {
    if (array == null || array.length == 0) {
      throw new IllegalArgumentException("array must be not empty!");
    }
    if (array.length == 1) {
      return array;
    }

    for (int i = array.length - 1; i > 0; i--) {
      for (int j = 0; j < i; j++) {
        if (array[j] > array[j + 1]) {
          swap(array, j, j + 1);
        }
      }
    }
    return array;
  }

  /**
   * 测试
   */
  public static void main(String[] args) {
    int[] array = {9, 8, 11, 17, 12, 2, 4, 5, 20, 3, 1};
    System.out.println("冒泡排序前:");
    for (int i = 0; i < array.length; i++) {
      System.out.print(array[i]);
      System.out.print(",");
    }
    array = BubbleSort.bubbleSort(array);
    System.out.println("\n冒泡排序后:");
    for (int i = 0; i < array.length; i++) {
      System.out.print(array[i]);
      System.out.print(",");
    }
  }
}

执行结果:

冒泡排序前:
9,8,11,17,12,2,4,5,20,3,1,
冒泡排序后:
1,2,3,4,5,8,9,11,12,17,20,
posted @ 2018-08-01 22:08  怀瑾握瑜XI  阅读(125)  评论(0编辑  收藏  举报