八大内部排序--希尔排序

来源:互联网 发布:软件缺陷生命周期 编辑:程序博客网 时间:2024/05/16 14:57

希尔排序(shell sort):先将整个带排序记录序列分割成若干个子序列分别进行直接插入排序,待整个序列的记录‘基本有序’时,再对全体记录进行一次直接的插入排序。

时间复杂度:O(n^1.5)  属于插入排序的一种,是稳定的排序

代码如下:

/***** shell-sort 希尔排序 稳定的排序 O(n^1.5)******/#include <iostream>using namespace std;void print(int *a,int n){    for(int i=0;i<n;i++){        cout<<a[i]<<" ";    }    cout<<endl;}void shell_sort(int *a,int n){    for(int step = n/2;step>=1;step/=2){        for(int i=step;i<n;i++){            if(a[i]<a[i-step]){                int val = a[i];                a[i] = a[i-step];                int j = i-step-step;                while(j>=0 && a[j]>val){                    a[j+step] = a[j];                    j-=step;                }                a[j+step] = val;            }        }    }}int main(){    int *a;    int n;    cin>>n;    a= new int[n+1];    for(int i=0;i<n;i++){        cin>>a[i];    }    shell_sort(a,n);    print(a,n);    return 0;}


0 0
原创粉丝点击