一、用途:
输入:n个数(a1,a2,...,an)
输出:输入序列的一个排列(即重新排序)<a1',a2',...,an'>,使得a1' <= a2' <= ...an'.
待排序的数成为关键字key.
Insertion-sort的参数是一个数组A[1,2,...,N],包含n个待排序的数.(在代码中,A中元素个数n用length[A]表示).输入的个数字是原地排序的(sorted in place),意即这些数字就是在数组A中进行重新排序的.在任何时刻,至多只有其中的常数个数字是存储在数组之外的.dang过程Insertion-sort执行完毕后,输入数组A中就包含了已经排好序的输出序列.
Insertion-sort(A)
1. for j <--- 2 to length[A]
2. do key <--- A[j]
3. Insert A[j] into the sorted sequence A[1....j-1]
4. i <--- j-1
5. while i > 0 and A[i] > key
6. do A[i+1] <--- A[i]
7. i <--- i-1
8. A[i-1] <--- key
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 package org.jacky.algorithm.insertion.sort; 2 3 public class InsertionSort { 4 private static final int[] arrays = { 5, 3, 4, 1, 2 }; 5 6 public static void main(String[] args) { 7 InsertionSort insertionSort = new InsertionSort(); 8 insertionSort.printArray(arrays); 9 insertionSort.executeSort(arrays); 10 insertionSort.printArray(arrays); 11 } 12 13 public void executeSort(int[] originalArray) { 14 if (originalArray == null || originalArray.length < 2) { 15 return; 16 } 17 for (int i = 1; i < originalArray.length; i++) { 18 int currentValue = originalArray[i]; 19 int position = i; 20 for (int j = i - 1; j >= 0; j--) { 21 if (originalArray[j] > currentValue) { 22 originalArray[j + 1] = originalArray[j]; 23 position -= 1; 24 } else { 25 break; 26 } 27 } 28 originalArray[position] = currentValue; 29 } 30 } 31 32 public void printArray(int[] array) { 33 System.out.print("{"); 34 for (int i = 0; i < array.length; i++) { 35 System.out.print(array[i]); 36 if (i < array.length - 1) { 37 System.out.print(", "); 38 } 39 } 40 System.out.println("}"); 41 } 42 }