【问题标题】:infinite loop in shell sort implementation in JavaScriptJavaScript中shell排序实现中的无限循环
【发布时间】:2020-04-23 00:28:26
【问题描述】:

我目前正在阅读Algorithms, 4th Edition by Robert Sedgewick 的第四版,其中作者有一个shell 排序的实现。我试图理解为什么这个实现在 JavaScript 中不起作用。虽然我可以console.log 排序后的数组,但程序似乎永远不会停止运行,它变成了一个无限循环。

 public class Shell
  {
     public static void sort(Comparable[] a)
     {  // Sort a[] into increasing order.
        int N = a.length;
        int h = 1;
        while (h < N/3) h = 3*h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
        while (h >= 1)
        {  // h-sort the array.
           for (int i = h; i < N; i++)
           {  // Insert a[i] among a[i-h], a[i-2*h], a[i-3*h]... .
              for (int j = i; j >= h && less(a[j], a[j-h]); j -= h)
                 exch(a, j, j-h);
           }
           h = h/3; }
         }
     // See page 245 for less(), exch(), isSorted(), and main().
}

以上是Java中的实现。请注意第一个循环 while (h &lt; N/3) h = 3*h + 1; 没有 {} 左大括号或右大括号,这是否意味着它一直到最后?

这是我在 JavaScript 中的实现:

function shellSort(a) {
  let N = a.length;
  let h = 1;

  while (h < N/3) {
    h = 3 * h + 1

    while (h >= 1) 
    {
      for (let i = h; i < N; i++) 
      {
        for (let j = i; j >= h && a[j] < a[j - h]; j -= h){
        let temp = a[j - h]
          a[j - h] = a[j]
          a[j] = temp
        }
      }
      console.log(a)
      h = h/3
    }
  }
}

console.log(shellSort([7,11,3,6,2,5,9,8,1,10]))

当我记录输出时,我得到了排序后的数组,但我不知道无限循环来自哪里。当你运行代码时,这是终端的输出:

  7, 8, 9, 10, 11
]
[
  1, 2, 3,  5,  6,
  7, 8, 9, 10, 11
]
[
  1, 2, 3,  5,  6,
  7, 8, 9, 10, 11
]
[
  1, 2, 3,  5,  6,
  7, 8, 9, 10, 11
]

有什么问题?我尝试将Math.floor 添加到h/3 但没有运气。 我做错了什么?

【问题讨论】:

  • 关于第一个循环,不,它并不代表你的想法。如果您不确定可以test it by itself to see what it does。请注意,在此示例中,“hello”仅打印一次。
  • 奇怪的是它在Java 中的工作方式,所以这不适用于我试过的javascript while(){} while{
  • 但这也没用

标签: javascript java algorithm sorting


【解决方案1】:

在Java中,整数除以整数仍然是整数:

int x = 5;
int y = x / 3;
// prints "1"
System.out.println(y);

然而,在 Javascript 中,没有整数,一切都是数字。那么,

let x = 5;
let y = x / 3;
// prints "1.6666666666666"
console.log(y);

您的算法要求h 为整数,否则很难将其用作数组索引。您必须将其显式转换为整数。修正了 Javascript 实现:

function shellSort(a) {
  let N = a.length;
  let h = 1;

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


  while (h >= 1) {
    for (let i = h; i < N; i++) {
      for (let j = i; j >= h && a[j] < a[j - h]; j -= h) {
        let temp = a[j - h]
        a[j - h] = a[j]
        a[j] = temp
      }
    }
    // parseInt here is key
    h = parseInt(h / 3)
  }

}
console.log(shellSort([7, 11, 3, 6, 2, 5, 9, 8, 1, 10]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2021-10-08
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    相关资源
    最近更新 更多