Direct insertion sorting refers to inserting elements to be sorted one by one into the previously sorted ordered sequence until all elements have been inserted. The main steps are as follows:
1) First assume that the first element has been sorted.
2) Then take out the next element that still needs to be sorted, that is, the next element after the sorted element, take out the next element, set it as the element to be inserted, and scan from back to front in the sorted element sequence. If the element (sorted) is larger than the element to be inserted, move the element to the next position.
3) Repeat step 2 until you find a position where the sorted element is less than or equal to the element to be sorted, and insert the element.
4) Repeat steps 2 and 3 to complete the sorting.
For example:
importjava.util.Arrays;publicclassMain{publicstaticvoidmain(Stringargs[]){int[]arr=newint[]{17,62,39,52,8,24};for(inti=1;i<arr.length;i++ ){//Start the comparison from the second element inttemp=arr[i];//Record the current element for(intj=i-1;j>=0;j--){//Start the comparison from the last element if (arr[j]>temp){//If it is larger than the current element arr[j+1]=arr[j];//Move all elements from here forward one position arr[j]=temp;/ /Insert the current element into arr[j]}}}for(inti=0;i<arr.length;i++){System.out.print(arr[i]+);}}}
The running results are as follows:
81724395262