Direct Insert Sort

Source: Internet
Author: User

1. The direct insert sort (straight insertion sort) is the simplest sort method, and its basic operation is to insert a record into the ordered sequential table, thus obtaining a new ordered table with a number of 1 records.

1 //-----------------The sequential table L as a direct insertion sorting algorithm--------------------2 voidInsertsort (SqList &L) {3      for(i=2; i<=l.length;++i)4         if(LT (l.r[i].key,l.r[i-1].key)) {//"(" to insert l.r[i] into an ordered sub-table5l.r[0] = L.r[i];//Copy as Sentinel6L.r[i] = l.r[i-1];7              for(j=i-2; LT (l.r[0].key,l.r[j].key);--j)8l.r[j+1] = L.r[j];//record and move back9l.r[j+1] = l.r[0];//Insert to correct positionTen         } One}//Insertsort

The time complexity of the direct insert sort is O (N2).

2. Binary Insert Sort

Because the basic operation of the insert sort is to find and insert in an ordered table. This "find" operation can be implemented using "binary find", in which the insertion sort is called binary insertion sort (Binary insertion sort).

1 //---------------The Order table L as binary insert sort---------------2 voidBinsertsort (SqList &L) {3      for(i=2; i<=l.length;++i) {4l.r[0] = L.r[i];//staging L.r[i] to l.r[0]5Low =1; High = i1;6          while(Low <= High) {//in R[low. High] binary find the position of an orderly insert7Mid = (low + high)/2;//binary8             if(LT (l.r[0].key,l.r[m].key))9High = mid-1;//insertion point in low half areaTen             Else     OneLow = mid +1;//insertion point in high half area A}// while -          for(j=i-1; j>=high+1;--j) -l.r[j+1] = L.r[j];//record and move back thel.r[high+1]=l.r[0];//Insert -}// for -}//Binsertsort

Binary insert sort requires additional storage space and direct insert sort, and from a time comparison, binary inserts only reduce the number of comparisons between keywords, and the number of moves recorded does not change. Therefore, the time complexity of binary insertion sorting is still O (N2).

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