An improved insertsort of the introduction of arithmetic in Exercise 2.3-6

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.