【问题标题】:Shellsort Interval Question JavaShellsort 间隔问题 Java
【发布时间】:2011-05-04 19:59:44
【问题描述】:

当我使用标准间隔大小以及使用非标准大小时,我需要测试 shellsort 的效率。我遇到的问题是当我尝试使用我的非标准间隔时。

当 h 等于标准区间大小时,这是我的 Shellsort:

    public void shellSort() 
    {
    int inner, outer;
    int temp;
    int h = 1;

    while (h <= length / 3)
    {
      h = h * 3 + 1; 
    }

    while (h > 0) 
    {

      for (outer = h; outer < length; outer++) 
      {
        temp = data[outer];
        inner = outer;

        while (inner > h - 1 && data[inner - h] >= temp) 
        {
          data[inner] = data[inner - h];
          inner -= h;
        }
        data[inner] = temp;
      }

      h = (h - 1) / 3; 

    }

  }

这是我尝试使用质数区间

      private int[]  primes = {0, 1, 3, 7, 13, 31, 97, 211, 503, 1013, 2503, 5171};
      public void shellSort() 
      {
        int inner, outer;
        int temp;
        int count = this.h.length - 1;
        int h = 1;

        h = primes[primes.length - 1] * 2 > length ? primes[primes.length - 1] : primes[primes.length - 2];

        while (h > 0) 
        {         
          for (outer = h; outer < length; outer++) 
          {
            temp = data[outer];
            inner = outer;

            while (inner > h - 1 && data[inner - h] >= temp) 
            {
              data[inner] = data[inner - h];
              inner -= h;
            }
            data[inner] = temp;
          }

          if(count - 1 > 0)           
              h = primes[count - 1];              

        }

      }

我试图根据实时效率比较两者,但我不知道如何让这个 prim 间隔起作用。

我正在尝试测试:

  • Shellsort performs better than O(N^2) with appropriately chosen interval sizes
  • 选择的一系列间隔大小对于实现优于 O(N^2) 运行时非常重要

感谢您的帮助。

【问题讨论】:

  • 这有什么问题?我认为它没有正确排序?还是你不知道如何计时?
  • 我知道如何计时,正是间隔本身将 shellsort 方法抛出到无限循环中,或者它没有正确排序。谁能告诉我素数区间计算是否正确?

标签: java algorithm sorting intervals shellsort


【解决方案1】:

您可能希望在外部循环的每次迭代中减少count 的值。在您的代码中,它仍然是this.h.length-1,即11。因此,在外循环的每次迭代之后,您都满足if 条件count-1 &gt; 0,所以您设置h = this.h[count-1],我相信它是2503。所以,你重新进入循环。

顺便说一句,调用间隔大小列表h 会严重影响可读性。你至少应该叫它hs

【讨论】:

  • 相信我,我从没想过那样做。我只是凭经验命名了我的数据,还没有机会重命名它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2012-11-28
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多