1. Algorithm concept.
Each time the first element is taken out of the unordered list and inserted into the appropriate position of the ordered list, so that the ordered list remains ordered.
2. Algorithmic thinking.
Assume that the records to be sorted are stored in the array R[1..n]. Initially, R[1] forms an ordered area, and the unordered area is R[2..n]. From i=2 until i=n, R[i] is inserted into the current ordered area R[1..i-1] in sequence, generating an ordered area containing n records.
public static void insertSort(int[] array) { int len = array.length; for (int i = 1; i < len; i++) { for (int j = i; j > 0; j--) { if ( array[j] < array[j - 1]) { Sort.swap(array, j, j - 1);//Exchange j and j-1 } else break; } } }
Insertion sort diagram:
The above is all the content shared with you in this article. I hope it will be helpful to everyone in understanding the insertion sort algorithm.