使用Ciura间隙序列在C ++中进行shell排序

时间:2014-05-05 23:37:47

标签: c++ sorting shellsort

我上课时有一个作业,并且我已经上了这个代码,但是我不确定我是否正确地做了,并且想要知道这个问题的人的一些意见。
他在这里为我们分配了“典型的”shell排序文件。

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;


template <typename Comparable>
unsigned long shellsort( vector<Comparable> & a )
{
  unsigned long counter = 0;

  for( unsigned int gap = a.size( ) / 2; gap > 0; gap /= 2 )
    for( unsigned int i = gap; i < a.size( ); i++ )
    {
      Comparable tmp = a[ i ];
      unsigned int j = i;

      for( ; j >= gap ; j -= gap )
      {
        counter++;
        if (!(tmp < a[ j - gap ])) break;
        a[ j ] = a[ j - gap ];
      }

      a[ j ] = tmp;
    }

  return counter;
}

const int N = 10000;

int main ()
{
  vector<int> rnumbers;
  clock_t start, finish;
  double duration;

  srand(42);
  start = clock();

  cout << "Sorting " << N << " numbers." << endl;

  for (int i=0; i<N; i++)
    rnumbers.push_back (rand ());

  finish = clock();
  duration = (double)(finish - start) / CLOCKS_PER_SEC;

  cout << "Initializing vector: " << duration << " seconds." << endl;

  start = clock();

  unsigned long comp = shellsort (rnumbers);

  finish = clock();
  duration = (double)(finish - start) / CLOCKS_PER_SEC;

  cout << "Sorting vector: " << duration << " seconds." << endl;
  cout << "Number of comparisons: " << comp << endl;

  return 0;
}

我们接下来必须使用修改代码来适应不同的间隙序列,即Ciura最佳间隙序列,然后使用公式计算更远但不到100万的数字。

int c[] = {510774, 227011, 100894, 44842, 19930, 8858, 3937, 1750, 701, 301, 132, 57, 23, 10, 4, 1};

他声明要修改代码,所以我只修改了这部分。

  unsigned long counter = 0;
  int x=0;
  int c[16] = {510774, 227011, 100894, 44842, 19930, 8858, 3937, 1750, 701, 301, 132, 57, 23, 10, 4, 1};
  for( unsigned int gap = c[x]; gap > 0; gap /= 2 )
  {
      x++;
    for( unsigned int i = gap; i < a.size( ); i++ )
    {

我仍然排序并且没有错误,但我无法帮助,但通过像我一样修改代码来思考,我并没有真正实现它之前已经做过的任何事情。

如果有人能帮助我,我会非常感激。

提前致谢。

1 个答案:

答案 0 :(得分:0)

不是通过gap /= 2计算下一个间隙值,而是应该迭代Ciura序列并依次使用每个值作为gap。所以不要这样做:

for( unsigned int gap = c[x]; gap > 0; gap /= 2 )

尝试类似:

for( int x = 0; x < 16; ++x )
{
    unsigned int gap = c[x];
    ...