Direct insertion sorting is the insertion of unsorted data into an appropriate position in the ordered sequence. The process is as follows: 1, first compare the array of the first two data, and sort, 2, compare the third element with the first two rows of data, and put the third element in the appropriate position, 3, compare the fourth element with the first three ordered data, and put the fourth element into the appropriate position; 4, until the last element into the appropriate position. If there is initial data: 25 11 45 26 12 78. 1, first compare the size of 25 and 11, 11 small, position interchange, the first round after sorting, the order is: [11, 25, 45, 26, 12, 78]. 2, for the third data 45, which is greater than 11, 25, so the position is unchanged, the order is still: [11, 25, 45, 26, 12, 78]. 3, for the fourth data 26, which is greater than 11, 25, less than 45, so it is inserted between 25 and 45, the order is: [11, 25, 26, 45, 12, 78]. ....... 4. The final order is: [11, 12, 25, 26, 45, 78]. The direct insert sort is stable. The average time complexity of the direct insert sort is O (N2). The Java code is implemented as follows:
1 Public voidSortint[] arr) {2 inttmp;3 for(inti = 1; i < arr.length; i++) {4 //data to be inserted5TMP =Arr[i];6 intJ;7 for(j = i-1; J >= 0; j--) {8 //determines whether the value is greater than TMP, or greater than9 if(Arr[j] >tmp) {TenARR[J+1] =Arr[j]; One}Else{ A Break; - } - } theARR[J+1] =tmp; -SYSTEM.OUT.PRINTLN (i + ":" +arrays.tostring (arr)); - } -}
The direct insertion sort of Java implementation of common algorithm