Sort-shell Sort

Source: Internet
Author: User

In the insert sort, all elements are compared to the previous element, and the position is replaced. So the number of exchanges is the square level of N. In extreme cases, if the smallest element is on the far right, you need to displace each and the preceding element individually. If you increase the interval between comparisons, you reduce the number of moves and then decrease the comparison interval at a successive intervals.

Thus the sequence of the comparison intervals is as follows H = 3*h+1.

The code is as follows:

1#include <iostream>2 3 using namespacestd;4 5 voidChangeint*p,intPOS1,intpos2);6 voidShellsort (int*p,intlength);7 voidPrintint*p,intlength);8 9 intMain ()Ten { One     intP[] = {2,5,3, One, the, the, -, -, the}; AShellsort (P,sizeof(p)/sizeof(int)); -Print (p,sizeof(p)/sizeof(int)); -cout <<"Hello world!"<<Endl; the     return 0; - } -  - voidPrintint*p,intlength) + { -      for(intI=0; i<length;i++) +cout << P[i] <<Endl; A } at  - voidShellsort (int*p,intlength) - { -     inth =0; -      while(h<length/3) -     { inH=3*h+1; -     } to      while(h>=1) +     { -          for(intI=1; i<length;i++) the         { *              for(intj=i;j>=h&&p[j]<p[j-1];j-=h) $             {Panax NotoginsengChange (p,j,j-h); -             } the         } +H = h/3; A     } the } +  - voidChangeint*p,intPOS1,intPos2) $ { $     if(POS1 = =Pos2) -     { -         return; the     } -     inttemp=P[POS1];WuyiP[POS1] =P[pos2]; theP[POS2] =temp; -}

It is still a challenge to understand the performance of shell sequencing, which requires expert effort, but the most important conclusion is that the run time is less than the square level of N.

Sort-shell 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.