Java sorting algorithm (vi): Direct Insert Sort
The basic operation of a direct insert sort is to insert the data element to be inserted into the preceding ordered sequence by the size of its keyword
Direct Insert sort time is not efficient, if in the worst case, the sum of all elements of the comparison is (0+1..n-1) = O (n^2). In other cases, consider the number of times the element is moved. So time complexity is O (n^2)
Direct insertion space is efficient and requires only one cache data unit, which means that the spatial complexity is O (1).
Direct Insert sort is stable
The direct insertion sort is more efficient in the case of data in a certain order. But if the data is irregular, you need to move a lot of data. Its efficiency is as bad as the bubble sort and selection sort.
Algorithm description
For a data sequence with n elements, the ordering requires a n-1 insert operation
The first pass inserts a second element into the preceding ordered subsequence-there is only one element at the front. Of course it's orderly.
The second pass inserts a third element into the preceding ordered subsequence. The first two elements are ordered.
N-1 Insert inserts the nth element into the preceding ordered sequence, preceded by the n-1 element is an ordered sequence
Code implementation
Packagecom.spring.test;Importjava.awt.print.Printable;/*** Direct insertion sorting algorithm*/ Public classInsertsorttest { Public Static voidMain (string[] args) {int[] data =New int[] {5, 3, 6, 2, 1, 9, 4, 8, 7 }; print (data); Insertsort (data); System.out.println ("Sorted Array"); print (data); } Public Static voidInsertsort (int[] data) { for(inti=1;i<data.length;i++){ //the element value at cache I intTMP =Data[i]; if(Data[i] < data[i-1]){ intj = I-1; //move the whole back one grid while(j>=0 && Data[j] >tmp) {Data[j+1] =Data[j]; J--; } //Finally, the TMP is inserted in the appropriate locationDATA[J+1] =tmp; print (data); } } } /*** Print Output*/ Public Static voidPrintint[] data) { for(inti=0;i<data.length;i++) {System.out.print (Data[i]+ "\ T"); } System.out.println (); } /*** Exchange Data*/ Public Static voidSwapint[] Data,intIintj) { if(i==j) { return; } Data[i]= data[i]+Data[j]; DATA[J]= data[i]-Data[j]; Data[i]= data[i]-Data[j]; }}
Run results
Java sorting algorithm (vi): Direct Insert Sort