First, the principle of insertion sorting
Insert a record into an ordered table that is already sorted, resulting in a new, ordered table with an additional 1 record count. Starting with the first element, consider the first element as an ordered subsequence, then insert the second element from the start of the second element, then get an ordered table of two elements, then insert the third element, get an ordered table of three elements ..., and so on, Until the last element is inserted correctly, the entire sequence is ordered.
Second, the pseudo-code implementation of the insertion sort
1insertion-SORT (A)2 forJ←2To Length[a]3 DoKey←a[j]4? Insert A[j] into the sorted sequence a[1.. j-1] to generate a new sorted sequence a[1: j]5I←j-16 whileI > 0 and A[i] >Key7 DoA[i + 1]←a[i]8I←i-19A[i + 1]←key
Third, the implementation of the Java source Code insertion sort
1 ImportJava.util.Comparator;2 3 4 Public classInsertsort {5 6 /**7 * Generic method implements insert sort algorithm,8 * A generic type cannot be of the underlying type, it must be a reference type9 */Ten Public Static<T>voidInsertsort (t[] T, comparator<?SuperT>comparator) { OneT key = T[0]; A for(intj = 1; J < T.length; J + +) - { -Key =T[j]; the //Insert the t[j] into the sorted sequence t[0, j-1], to generate a new sorted sequence t[0, j] - inti = J-1; - while(I >-1 && comparator.compare (T[i], key) > 0) - { +T[I+1] =T[i]; -i--; + } AT[I+1] =key; at } - } - - /** - * @paramargs - */ in Public Static voidMain (string[] args) { - //TODO auto-generated Method Stub toInteger[] INTs = {2, 0, 5, 23, 1, 4, 8, 56, 19}; +Insertsort (INTs,NewComparator<integer>(){ - Public intCompare (integer O1, integer o2) { the returnO1.intvalue ()-O2.intvalue (); * } $ });Panax Notoginseng - for(inti = 0; i < ints.length; i++) the { +System.out.print (Ints[i] + ""); A } the System.out.println (); + } - $}
Operation Result:
Iv. Analysis of Complexity
O (n^2)
java-Sorting algorithm-insert Sort