簡體   English   中英

shell 中的無限循環 JavaScript 中的排序實現

[英]infinite loop in shell sort implementation in JavaScript

我目前正在閱讀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]))

當我記錄 output 時,我得到了排序后的數組,但我不知道無限循環來自哪里。 當您運行代碼時,這是 output 到終端的內容:

  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但沒有運氣。 我做錯了什么?

在 Java 和 integer 除以 integer 仍然是 Z157DB7DF53002375EZ15B76

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為 integer,否則很難將其用作數組索引。 您必須將其顯式轉換為 integer。 修正 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]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM