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