0

我有一个 Java 代码,它运行良好,但是转换为 JavaScript 的代码会引发错误。ShellSort 方法将一个数组传递给该方法。(我正在使用控制台进行调试)我的代码是:

this.shellSort = function(nums)
    {
//O contador de tempo inicia aqui
    var tempoSS = new Date();
    var n = nums.length;
    console.log("n = ",n);
    var h = n / 2;
    console.log("h = ",h);
    var c, j;
    while (h > 0)
    {
        for (var i = h; i < n; i++)
        {
            c = nums[i];
            j = i;
            while (j >= h && nums[j - h] > c)
            {
                nums[j] = nums[j - h];
    console.log("nums["+j+"] = ",nums[j]);
                j = j - h;
    console.log("j = ",j);
            }
            nums[j] = c;
    console.log("nums["+j+"] = ",nums[j]);
        }
        h = h / 2;
    console.log("h = ",h);
    }

捕获的错误是-- [13:52:59.581] ReferenceError: reference to undefined property nums[(j - h)] @ file:///C:/Documents%20and%20Settings/erickribeiro/Desktop/www/index.html:240

测试页面:dev.erickribeiro.com.br/index.html

完整的脚本是 html 页面。怎么了?

4

1 回答 1

0

我相信您会陷入无限循环,因为h有时可能会浮动。你必须确保它是一个整数(在 Java 中它总是这样,因为你可能这样声明它):

this.shellSort = function(nums)
    {
//O contador de tempo inicia aqui
    var tempoSS = new Date();
    var n = nums.length;
    console.log("n = ",n);

    // HERE:
    var h = Math.floor(n / 2);

    console.log("h = ",h);
    var c, j;
    while (h > 0)
    {
        for (var i = h; i < n; i++)
        {
            c = nums[i];
            j = i;
            while (j >= h && nums[j - h] > c)
            {
                nums[j] = nums[j - h];
    console.log("nums["+j+"] = ",nums[j]);
                j = j - h;
    console.log("j = ",j);
            }
            nums[j] = c;
    console.log("nums["+j+"] = ",nums[j]);
        }

        // AND HERE:
        h = Math.floor(h / 2);
    console.log("h = ",h);
    }
}
于 2013-02-05T16:07:40.243 回答