排序算法(Shell Sorting希尔排序)

希尔排序可以说是基于插入排序的一种更高级的排序算法。它是原址排序,但不稳定,时间复杂度

  1. 它与插入排序的不同之处在于,它将待排的序列以间隔为 取出,这样把整个待排序序列分成若干个子集,然后对子集序列用插入排序法进行排序;
  2. 再令 ,再次进行与第一步类似的步骤;
  3. 直到 , 完成最后一次排序后,待排序序列就完成排序了。

PS 注意: Shell排序有一个关键步骤是序列选取间隔 的选择,首先可令它为待排序列长度的一半

下面以VS2010运行环境给出了实现代码,且当待排序的序列的个数N=20(较小)时,运行结果如下:

N较小时给出了排序前和排序后的序列

当N=10000时,排序时间为如下:
The sorted-time spending is 3 ms


下面给出Shell排序的代码片段

void Shell_Sort(int *arr)
{ //Codes of the Shell_Sort  Algorithm
    if(NULL==arr)
        throw exception("Invalid parameters.");
    int ii,increment,flag,temp;
    for(increment=N/2;increment>0;increment/=2)
        for(ii=increment;ii<N;++ii){
            temp=arr[ii];
            flag=ii-increment;
            while(flag>=0 && arr[flag]>temp){
                arr[flag+increment]=arr[flag];
                flag-=increment;
            }
            flag+=increment;
            arr[flag]=temp;
        }
}
//主函数与其他子函数
#include "stdafx.h"
#include <iostream>
#include <exception>
#include <ctime>
using namespace std;

const int N=20;//待排序序列的个数
const int Range=3000;//待排序序列的大小范围
void Swap(int &,int &);
void InputNumber(int *,int );
void OutputNumber(int *,int);
void Shell_Sort(int *);

int _tmain(int argc, _TCHAR* argv[])
{
    int arr[N]={0};
    InputNumber(arr,N);
    cout<<"The InputNumbers are--------------"<<endl;
    OutputNumber(arr,N);
    auto tstart=clock();
    Shell_Sort(arr);
    auto tend=clock();
    auto TotalTime=tend-tstart;
    cout<<"The sorted-time spending is "<<TotalTime<<" ms"<<endl;
    cout<<endl<<"The Sorted Numbers are--------------"<<endl;
    OutputNumber(arr,N); 
    return 0;
}

void InputNumber(int *arr,int N)
{
    if(arr==NULL)
        return;
    for(int ii=0;ii<N;++ii)
        arr[ii]=rand()%Range;
}

void OutputNumber(int *arr,int N)
{
    for(int ii=0;ii<N;++ii)
        cout<<arr[ii]<<'\t';
    cout<<endl;
}

inline void Swap(int &lhs,int &rhs)
{
    int temp;
    temp=lhs;
    lhs=rhs;
    rhs=temp;
}

下面一篇将介绍快速排序,也同样的给出了实现代码和排序运行时间

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值