Sedgewick增量希尔排序和快速排序 (附C++代码)

01 运行时间比对结果

随机数组长度为10000时:

快速排序:1452

希尔排序:2122

随机数组长度为100000时:

快速排序:19156

希尔排序:29806

02 Show me the code

// Sedgewick增量希尔排序
template <class T>
void heelSort(T origin[], const long SIZE){
    const unsigned long Sedgewick[] =
    {1, 5, 19, 41, 109, 209, 505, 929, 2161,
        3905, 8929, 16001, 36289, 64769, 146305,
        260609, 587521, 1045505, 2354689, 4188161,
        9427969, 16764929, 37730305, 67084289,
        150958081, 268386305, 603906049, 1073643521};

    unsigned long i = 0;
    long keeper = 0;
    for(; i < 28; ++i){

        if(Sedgewick[i] > SIZE){
            keeper = i - 1;
            break;
        }

    }

    while (keeper >= 0) {
        i = Sedgewick[keeper];
        unsigned long j = i;

        while (j < SIZE) {
            unsigned long p = j;
            T temp = origin[p];

            while ( (p >= i) && (origin[p - i] > temp)) {
                origin[p] = origin[p - i];
                p -= i;
            }

            origin[p] = temp;
            j++;
        }

        keeper--;
    }
  
}


// 快速排序
template <class T>
void quickSort(T origin[], const long SIZE) {
    if (SIZE > 1) {
        T base = origin[0];
        long left = 0;
        long right = SIZE - 1;

        while (left != right) {

            while (left != right && origin[right] >= base) {
                --right;
            }
            origin[left] = origin[right];

            while (left != right && origin[left] <= base) {
                ++left;
            }
            origin[right] = origin[left];
        }

        origin[left] = base;
        quickSort(origin, left);

        if (left != SIZE - 1) {
            quickSort(origin + left + 1, SIZE - left - 1);
        }

    }
}

测试代码

#include 
#include 
#include 

using namespace std;


/*
 * 此处为上面的两个排序函数
 */


int main() {
    const int N = 100000;
    int ar1[N], ar2[N], ar3[N];
    int ct;
    
    // 构建随机数组
    for (int i = 0; i < N; ++i) {
        ct = rand() % N;
        ar1[i] = ct;
        ar2[i] = ct;
        ar3[i] = ct;
    }
    
    // 库函数,用来验证排序结果是否正确
    sort(ar1, ar1 + N);
    
    // 快速排序测试计时
    auto start = clock();
    quickSort(ar2, N);
    cout << "quick    " << clock() - start << endl;
    
    // 希尔排序测试计时
    start = clock();
    heelSort(ar3, N);
    cout << "heel    " << clock() - start << endl;
    
    // 与库函数排序结果进行比对
    for (int i = 0; i < N; ++i) {
        if ((ar1[i] - ar2[i] != 0) || (ar1[i] - ar3[i] != 0)) {
            cout << "error" << endl;
            break;
        }
    }
    
    return 0;
}

你可能感兴趣的:(算法)