排序_Shell_Sort(希尔排序)更正版

来源:互联网 发布:python抓取手机号 编辑:程序博客网 时间:2024/05/16 06:10

希尔排序,可以更正的一点就是,增量是设计成偶数,还是设计成奇数,还是不用去管它,是什么样就是什么样呢?

通过看前任的研究,可以发现,增量设计成奇数是可以减少点计算量的,但效果也不会很明显.呵呵,不过,做知识还是要严谨一些比较好.

贴出代码:

#include <stdio.h>#include <string.h>#include <math.h>#include <iostream>#include <string>#include <algorithm>using namespace std;int N;int a[1000];void Shell_Sort ()//关于希尔排序的增量为奇数好还是为偶数好,上网查了查是奇数好,次数会少点,自己研究不出来为什么//是奇数好,但是都这样说,自己就只能按照奇数的增量来分组了. {int d = (N >> 1) % 2 == 0? N >> 1 + 1 : N >> 1; //注意这里,一定要让增量变成是奇数 while (d > 0){for (int i = d; i < N; i++){int  j = i - d;int t = a[i];while (j >= 0 && t < a[j]){a[j + d] = a[j];j -= d;}a[j + d] = t;}for (int i = 0; i < N; i++){cout << a[i] << " ";}cout << endl;
if (d == 1) break; //这个是非常重要的...晕,前面写错了...也没有检查出来,因为要估计到奇数就会少算很多次数,就得加这一句话.要不然是死循环的;d = (d >> 1) % 2 == 0 ? d >> 1 + 1 : d >> 1; //也要注意这里 也要保证增量是奇数. }}int main(){cout << "Input the number that you want be sorted : " << endl;cin >> N;cout << "Please input the numbers:  " << endl;for (int i = 0; i < N; i++){cin >> a[i];}Shell_Sort ();for (int i = 0; i < N; i++){cout << a[i] << " ";}cout << endl;system ("pause");return 0;}