Parse the shell sort implementation code

  • 2020-04-01 23:34:32
  • OfStack


#include <iostream> 
using namespace std; 
void ShellQin(int A[],int n) 
{ 
    int gap=n/2; 
    int i,j; 
    for(;gap>0;gap=gap/2)//Set the initial gap, group by gap, and decrement by gap/2
    { 
        //Once the gap is set, insert sort for each element in its corresponding group from the gap all the way to the last element. The gap should be the second element at the position of the group, and the first element at position 0
        for(i=gap;i<n;i++) 
        { 
            j=i; 
            //Insert sort a group
            if(A[j-gap]>A[j]) 
            { 
                
                int temp=A[j];//Save A [J].
                do
                { 
                    A[j]=A[j-gap]; 
                    j=j-gap; 
                }while(j>=0&&temp<A[j]);//Move back every number greater than A[j]
                A[j+gap]=temp;//Insert A[j] into the appropriate position
            } 
        } 
    } 
    for(i=0;i<n;i++) 
    { 
        cout<<*(A+i)<<" "; 
    } 
} 
int main1() 
{ 
    int a[]= {5,4,3,21,1,100,93,1,3,2,4}; 
    ShellQin(a,11); 
    return 0; 
}

After discussion with my friend, although the worst case of hill and block is n squared, I think the reason why the efficiency of hill is better than block is that the coefficient in front of the time complexity is smaller than block, especially in reverse order, which obviously reduces the number of comparisons. Just like quicksort to heap, the coefficient in front of quicksort is much smaller than heap, plus it is easy to use, so it is called programmers' favorite.
The following algorithm, also known as shell sort, differs from the above in that when insertion sort is performed, the shift is replaced by the exchange of adjacent data (i.e., the key keyword is removed first, and the value greater than key is shifted backward).

//Swap two decimals
void swapdouble(double *a,double *b){ 
   double temp=*a; 
   *a=*b; 
   *b=temp; 
} 
void Shell(double* p,int n) 
{ 
    int gap=n/2; 
    int i,j; 
    for(;gap>0;gap=gap/2) 
    { 
        for(i=gap;i<=n-1;i++)//Insert sort for each group you are in starting with the gap, where I =gap is the second element
        { 
            j=i; 
            if(*(p+j)<*(p+j-gap)) 
            { 
                while(j>=gap && *(p+j)<*(p+j-gap)) 
                { 
                    swapdouble(p+j,p+j-gap); 
                    j=j-gap; 
                } 
            } 
        } 
    } 
}


Related articles: