Direct Insert Sort:
In daily life, this sort of sorting problem is often encountered: inserting new data into columns that are already sorted.
For example: A set of data columns from small to large rows {1,2,3,4,5,6,7,9,10}, often called sequences, we use the ordinal number, ... Represents the location of the data in order to insert a new data 8 into the above sequence.
Steps to complete this work: ① determines the number of positions that the data "8" should occupy in the original sequence. The data "8" should be located at a location that is less than or equal to all data on the right side of the position, greater than all data on its left position. ② the location, inserting the data "8". The way to insert a sort directly (straight insertion sort) is to remove the first element from the unordered table each time, insert it into the proper position of the ordered table, and make the ordered table still orderly. For example: The original ordered table: (9 15 23 28 37) 20 Find the insertion position: (9 15 ^ 23 28 37) 20 New ordered table: (9) Java implementation:
1 Packageusually used;2 Public class_1 Direct Insert Sort {3 Public Static voidMain (string[] args) {4 inta[]={3,5,6,2,4,1};5 for(inti=1;i<a.length;i++){6 if(A[i] <a[i-1]) {//If reverse order occurs, insert forward7 intj,temp;8temp=A[i];9 for(j=i-1;j>=0&&temp<a[j];j--){TenA[J+1]=A[J];//move the value greater than temp to one unit after the whole One } A //insert to the specified location -a[j+1]=temp; - the } - } - - for(inti=0;i<a.length;i++){ + System.out.print (A[i]); - } + } A}
JS implementation:
1 functionZhijieinsertsort (a) {2 vari,j,temp;3 for(i = 1;i<a.length;i++) {4 if(A[i] <a[i-1]) {//If reverse order occurs, insert forward5temp =A[i];6 for(j = i-1;j>=0&&a[j]>temp;j--) {7A[J+1] =A[j];8 }9A[J+1] =temp;Ten } One } A } - varA =NewArray (7,2,6,5,1,4,3); - Zhijieinsertsort (a); thedocument.write ("_1 Direct Insert Sort" +a+ "<br/>")
Sort algorithm-insertion sort--insert sort directly