A key step in Insertsort is to insert the current element A[i] into the proper position of the already sequenced a[1,i-1], in the original Insertsort algorithm,
Using the method of searching from the back to the next step, exercise 2.3-6 requires the use of binary search in exercise 2.3-5 to speed up the insertion process.
The binary search algorithm is slightly modified to return the correct position of the inserted element:
Public Static intFindinsertplace (int[] A,intTargetintAintb) {intMiddle = a + (b-a)/2; if(a>b)returnA; Else if(a[middle]==target)returnMiddle; Else if(a[middle]<target)returnFindinsertplace (a,target,middle+1, B); Else returnFindinsertplace (a,target,a,middle-1); }
The only difference between findinsertplace and binary search is that:
if (a>return A;
Students can draw a picture, test whether it is right or wrong.
The improved Insertsort is as follows:
Public classImprovedinsertsort { Public Static voidSortint[] A) { for(inti = 1; i<a.length;i++) { inttemp =A[i]; intInsertplace = Findinsertplace (a,temp,0,i-1); for(intJ= i-1; j>=insertplace; j--) A[j+1] =A[j]; A[insertplace]=temp; } return ; } Public Static intFindinsertplace (int[] A,intTargetintAintb) {intMiddle = a + (b-a)/2; if(a>b)returnA; Else if(a[middle]==target)returnMiddle; Else if(a[middle]<target)returnFindinsertplace (a,target,middle+1, B); Else returnFindinsertplace (a,target,a,middle-1); } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub intA [] ={1, 7,5,5, 2, 4, 6, 7,4,23,11,34,15}; Improvedinsertsort.sort (A); for(inta:a) System.out.print (a+" "); }}
Prior to the improvement, Insertsort was O (n^2) in the worst case, and after the improvement, it was O (N*LG (n)), which greatly improved the efficiency of the algorithm.
An improved insertsort of the introduction of arithmetic in Exercise 2.3-6