In the previous summary, the main practice of the algorithm in the ordering of the choice of sorting. So let's move on to the two types of insertion sort: the direct insert sort and the hill sort algorithm.
----- Direct - connect insertion sort
Package com.sort;/** * Direct Insert sort * * @author Weixing-yang * * algorithm ideas: * Each step inserts an element to be sorted into the appropriate position in the previously sorted set of elements, *< c4/> until all the elements have been cleared. */public class Insertionsort {public void Insertionsort (int[] arr, int n) {for (int i = 1; i < n-1; i++) {int temp = arr[i];//gets the second element if (Temp < arr[i-1]) {int j;for (j = i-1; J >= 0 && arr[j] > temp; j--) {arr[j+1] = arr [j];} ARR[J+1] = temp;}}}}
-----Hill Sort
The Hill sort (Shell sort) is one of the insertion sorts, which is to cut the entire sequence into several small sub-sequences for insertion sorting.
Package com.sort;/** * Hill Sort * @author Weixing-yang * * Algorithm idea * First take out a positive integer d1<n, place all the elements separated by D1 in a group. Direct insert sort within each group. * then take D2<D1, repeat the above grouping and sorting operations. Until di = 1, where all records are sorted in a group. * */public class Shellsort {public void Shellsort (int[] arr, int n) {int i,j,k,temp;k = (n-1)/2;while (k > 0) {for (i = k; i < n-1; i++) {temp = Arr[i];for (j = i-k; J >= 0 && arr[j] > temp; J-= k) {Arr[j+k] = arr[j];} ARR[J+K] = temp;} k/=2;}}}
-----test function
Package Com.sort;public class Main {public static void main (string[] args) {int[] array = {$, a, 45,40, N, A, v}; int n = array.length;insertionsort insert = new Insertionsort (); Shellsort shell = new Shellsort (); Long start = System.currenttimemillis ();//insert.insertionsort (array, n); Shell.shellsort (array, n); long end = System.currenttimemillis (); Long sum = End-start; SYSTEM.OUT.PRINTLN ("Total number of milliseconds spent in sorting:" +sum); for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]+ "");}}
-----Execution Results
The direct insertion sort is a stable sort, the time complexity is N2, and the hill sort is unstable sort.
@@ ZZFCTHOTFIXZ >> Next chapter to continue practice two sort algorithms for merge sort .
Essentials of data structure------direct insertion sorting and hill sorting algorithms