【发布时间】: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 < 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中的工作方式,所以这不适用于我试过的javascriptwhile(){} while{ -
但这也没用
标签: javascript java algorithm sorting