Sort algorithm--insert Sort

Source: Internet
Author: User

First, insert sort (insertion sort)

 void  insertionsort (vector<int  > &a) { for  (int  i=1 ; i<a.size (); ++i) {int  tmp=a[i];        int   J;  for  (J=i;j>0  &&tmp< A[j-1 ];--j) {a[j]  =a[j-1  ];  //  insert tmp in the correct location  A[j]=TMP; }      }    


each time a record to be sorted is inserted in its size into the previously ordered Subsequence (with the fact that the element on the known position 0 to position i-1 is already in an ordered state)


1) Initially, A[0] into an orderly area, a[1,...., N-1] is a disorderly area, so that I=1

2) Merge A[i] into the current ordered area a[0,..., I-1], forming a new ordered area a[0,...., i]

Select the first a[i of the unordered area] as TMP, compare with the ordered area, move all elements greater than TMP (before position I) to the right, stop when a[j]<tmp is found, insert tmp at A[J+1]

3) I plus 1, repeat 2), until finished a[n-1], sort complete

Complexity of Time:

1) within the cycle, the number of tests for each I value is i+1 times (when the input is reversed), the number of tests in the inner loop is (2+3+...+n) =θ (N2);

2) If the input is ordered (positive order), then the inner loop is not executed, the running time is O (N);

The average run time is O (N2).

Second, the shell sort

Sort algorithm--insert Sort

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: 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.