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 に答える