C++模板实现希尔排序

来源:互联网 发布:手机能注册淘宝账号吗 编辑:程序博客网 时间:2024/05/21 08:47

希尔排序是一种高效的排序算法,原理是将大数组分成若干个小数组,对每个小数组进行排序.之后缩短步长,对原数组重新划分小组,继续对每个小组进行排序.直到步长变为1后,进行最后一次直接插入排序.
此算法高效的原因在于直接插入排序在对基本有序的序列进行排序是十分高效的.前期划分子数组进行排序,可以逐渐使得较大的元素排列在原序列的尾部,符合插入排序高效的前提条件.

步长的经验值以如下公式得出:
h1 = 1;
h(n) = 3*h(n-1)+1

算法特点:
1.不稳定
2.时间复杂度O(n1.3)
3.终止条件,步长缩短为1.

算法实现如下:

//Combsort//1. Not Stable//2. Time complex O(n1.3)//3. Space complecity, ?//4. Terminate condition, increase step decrease to 1template <typename T>void Sort<T>::shellSort(T* const sortArray, const unsigned int size){    if (size < 10)    {        cout << "The array is so small, no need shell Sort, use direct insert sort is fine!" << endl;        directInsertSort(sortArray, size);    }    else    {        int increaseArray[20]; //This could support to the max unsigned int in 32bit program        int h = 1;        int increaseArrayNum = 0;        for (int i = 0; h < size; i++)        {            //loopTimes++;            increaseArray[i] = h;            h = 3 * h + 1;            increaseArrayNum++;        }        for (int i = increaseArrayNum - 2; i >= 0; i--)        {            int increaseStep = increaseArray[i];            for (int j = 0; j < increaseStep; j++)            {                for (int k = j + increaseStep; k < size; k = k + increaseStep)                {                    T insertValue = sortArray[k];                    for (int l = k; (l - increaseStep) >= 0; l = l - increaseStep)                    {                        loopTimes++;                                                if (sortArray[l] < sortArray[l - increaseStep])                        {                            sortArray[l] = sortArray[l - increaseStep];                            sortArray[l - increaseStep] = insertValue;                            moveTimes++;                        }                        else                        {                            break;                        }                    }                }            }        }    }    return;}
0 0
原创粉丝点击