Basic principle
Direct Insertion Method idea:1. In raw data, the first data is used as a sorted data series2. Get the next element from the array, scan it from the back forward in the sorted element, and determine the size of the element and the arranged3. If the element of the sort sequence is greater than the new element, move the element to the next position4. Repeat step three until you find that the sorted element is less than or equal to the position of the line element5. Insert a new element into the location6. Repeat steps 2~5 until data processing is complete
For example
Array to sort
"38,65,97,76,13,27,49"
Sorting process
First trip Insert 38: "65,97,76,13,27,49,"
Second trip Insert 65: "38,65,97,76,13,27,49"
Third trip Insert 97: "38,65,97, 76,13,27,49"
Four times Insert 76: "38,65,76,97,13,27,49"
Five times Insert 13: "13,38,65,76,97, 27,49"
Six times Insertion 27: "13,27,38,65,76,97,49"
Seventh trip Insert 49: "13,27,38,49,65,76,97"
"Code Implementation"
PackageCom.sort; Public classTestinsertsort { Public Static int[] Insertsort (int[] a) { intLength=a.length; inti,j,tmp; for(i=1;i<length;i++) {tmp=a[i];//Take out an unsorted data for(j=i-1;j>=0&&a[j]>tmp;j--) {//find a location in a sort sequenceA[J+1]=A[J];//data moves backwards without worrying about being overwritten, because TMP saves the first overwritten data} a[j+1]=tmp;//Insert the data because the for loop above is executed at the end of the j--, so the value is assigned a[j+1] } returnA; } Public Static voidMain (string[] args) {inta[]={2,9,0,8,7,1,5,4,3,6}; A=Insertsort (a); for(inti=0;i<a.length;i++) {System.out.print (A[i]+" "); } }}
02_ Sort _ Insert Sort