算法学习之排序(4)--Shell排序

一.算法描述

   Shell排序试图将待排序序列变成基本有序的,然后再用插入排序来完成最后的排序工作。
   Shell排序通过将比较的全部元素分为几个区域来提升插入排序的性能。这样可以让一个元素可以一次性地朝最终位置前进一大步。然后算法再取越来越小的步长进行排序,算法的最后一步就是普通的插入排序,但是到了这步,需排序的数据几乎是已排好的了(此时插入排序较快)。

二.时间复杂度

    对于Shell排序而言,最差情况下的时间复杂度与步长的大小有关,具体情况如下:

三.空间复杂度

    Shell排序是in-place排序,因此空间复杂度为O(1).


四.C++实现

   为了方便使用前面写过的插入排序,我的实现是将子序列复制出来,使用插入排序进行排序之后再复制回去原来的数组中,因此,我的实现过程并不是in-place的,但是,Shell排序本身是in-place的。
#include <iostream>

#include "Sort.h"


bool InsertSort(std::vector<int>& Array)
{
    // return false if the array is empty.
    if (Array.empty())
    {
        std::cout << "The size of the Array is empty." << std::endl;
        return false;
    }

    // return the origin array if there are only one element of the array
    if (Array.size() == 1)
    {
        std::cout << "The size of the array is one." << std::endl;
        return true;
    }


    int Size = Array.size();
    for (int Index = 1; Index < Size; Index++)
    {
        int Value = Array[Index];

        int TrueIndex = Index - 1;

        // find the index of the Value
        for (; TrueIndex >=0; TrueIndex--)
        {
            if (Array[TrueIndex] <= Value)
            {
                break;
            }

            Array[TrueIndex + 1] = Array[TrueIndex];
        }

        // put the value to the TrueIndex
        Array[TrueIndex + 1] = Value;
    }

    return true;
}



五.参考文献

[1] Shaffer C A. Practical Introduction to Data Structure and Algorithm Analysis (C++ Edition)[J]. 2002.
[2] 科曼 and 金贵, 算法导论: 机械工业出版社, 2006.
[3] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, "算法导论 (影印版)," ed: 北京: 高等教育出版社.
[4]http://zh.wikipedia.org/wiki/%E5%B8%8C%E5%B0%94%E6%8E%92%E5%BA%8F



版权所有,欢迎转载,转载请注明出处,谢谢微笑







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值