排序算法 — 插入排序

/**
 * 插入排序
 *
 * <p>算法思路:
 *
 * <p>1.选取数列第一个数作为已排序,数列的其他部分作为待排部分
 * <p>2.每次取待排部分的第一个元素待插入数,然后从已排序部分末尾开始遍历,直到找到比待插入数小(或者打)的数
 * <p>3.将这个小的数的位置后的数往后移动,空出一位,再将待插入数插入
 * <p>4.重复以上步骤,直到无待排部分
 *
 * 算法复杂度:O(n²)
 * 稳定性:稳定
 * @author lxy
 */
public class InsertSort {


  public static int[] insertSort(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 = 0; i < array.length; i++) {
      int waitIns4Index = i;
      int waitInsert = array[i];
      for (int j = i - 1; j >= 0; j--) {
        if (waitInsert < array[j]) {
          array[j + 1] = array[j];
          waitIns4Index = j;
        } else {
          break;
        }
      }
      array[waitIns4Index] = waitInsert;
    }
    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 = InsertSort.insertSort(array);
    System.out.println("
插入排序后:");
    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,

原文地址:https://www.cnblogs.com/lxyit/p/9404231.html