【排序】希尔排序

程序代码:

//Shell排序 
#include<iostream>
using namespace std;
void ShellSort(int* r,int n);
int main()
{
    int num[11];
    for(int i=1;i<11;i++)
        cin>>num[i];

    ShellSort(num,10);
    for(int i=1;i<11;i++)
        cout<<num[i]<<' ';

    return 0;
} 
void ShellSort(int* r,int n)
{
    int step = (n+1)/2;
    int temp;
    int i=step+1;
    int j;
    while(step>1)   
    {
        while(i<=n)          //直接插入排序的流程
        {
            temp = r[i];
            j=i-step;
            while(j>0&&r[j]>temp)
                {
                    r[j+step]=r[j];
                    j=j-step;
                }   
            r[j+step]=temp; 
            i++;    
        }
        step = (step+1)/2;
        i=step+1;
    }
    //此时step==1
    while(i<=n)
        {
            temp = r[i];
            j=i-step;
            while(j>0&&r[j]>temp)
                {
                    r[j+step]=r[j];
                    j=j-step;
                }   
            r[j+step]=temp; 
            i++;    
        }
}

运行结果:

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务