Started learning algorithm from 0 - Sort (1.4 Shell sort)

Algorithms understand:

  Hill sorting is optimized insertion sort, insertion sort may be because a more orderly and efficient data processing, this full Hill sorting a specialty, in Hill sorting, the program is repeated at intervals of non-selection of the elements is not h insertion sort objects.

  Below, on the A [] = {4,8,9,1,10,6,2,5,3,7}; H = {4,3,1} for the shell sort.

 

 

 

 

 

#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>

using namespace std;

const  int maxn 1E5 + = 1 ;
long  long cnt;
int l;
int A [maxn]
 int n;
vector<int >G;

// specified gap g is tampered sort 
void InsertionSort ( int A [], int n-, int g) {
     for ( int I = g; I <n-; I ++ ) {
         int V = A [I];
         int J = I - G;
         the while (J> = 0 && A [J]> V) {
            A[j+g]=a[j];
            j-=g;
            cnt++;
        }
        A[j+g]=v;
    }
}

void shellSort(int A[],int n){
    //生成数列1,4,13,40,121,364,1093
    for(int h=1;;){
        if(h>n)break;
        G.push_back(h);
        h=3*h+1;
    }
    
    for(int i=G.size()-1;i>=0;i--){//逆序指定g
        insertionSort(A,n,G[i]);
    }
}

int main () {
    scanf("%d",&n);
    
    for(int i=0;i<n;i++){
        scanf("%d",&A[i]);
    }
    cnt=0;
    
    shellSort(A,n);
    
    for(int i=G.size()-1;i>=0;i--){
        printf("%d",G[i]);
        if(i)printf(" ");
    }
    printf("\n");
    printf("%d\n",cnt);
    for(int i=0;i<n;i++){
        printf("%d\n",a[i]);
    }
    
    return 0;
}

1. want to sort data must then complete the final performance g = 1, i.e. the ordinary insertion sort

There are many methods 2.G array selection, when G is 1,4,13,40,121, etc. i.e. G n-+ 1 = G n- * 3 + 1, then substantially maintained complexity O (N 1.25 )

3. encountered exponent of 2, then g = 1 requires little before the array arrangement, Hill sorting efficiency greatly reduced

Guess you like

Origin www.cnblogs.com/wz-archer/p/11676362.html