Skip to main content

Insertion Sort

插入排序i元素插入到下标为0~i-1的位置上,逐个比较,如果发现前面的元素比arr[i]大 则将该元素后移 否则将i元素放入到空位置上

package whale.simpleAlgorithm;


/**
* @Author: WhaleFall541
* @Date: 2021/4/4 16:08
*/
public class SimpleSort {

public static void main(String[] args) throws InterruptedException {

int[] arr = {-1111, 20, -3, -10, 100, -255};

insertSort(arr);
StringBuilder sb = new StringBuilder();
for (int i : arr)
sb.append(i).append(" ");
System.out.println("sb = " + sb);

}

// 插入排序
private static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
// 需要将i插入到前面子序列
if (arr[i] < arr[i - 1]) {
int k = arr[i], j;
// i为要插入的元素,j为i往前的元素
// 如果arr[j]比k大 则把arr[j]元素往后挪
// 如果arr[j]比k小则直接插入元素在空位上
for (j = i - 1; j >= 0 && arr[j] > k; j--)
arr[j + 1] = arr[j];
// 将元素放到比k小的后面
arr[j + 1] = k;
}
}
}
}

Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
  • Attribution: Retain the original author's signature and code source information in the original and derivative code.
  • Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
The documentation part of this work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License . You may freely share, including copying and distributing this work in any medium or format, and freely adapt, remix, transform, and build upon the material. However, you are required to:
  • Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
  • NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
  • ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.