程序在jumpsearch中无限运行

时间:2019-06-30 14:36:33

标签: javascript

arr = [ 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ] 

const JumpSearch = (arr, num) => {
    const length = arr.length;
    const eachBlock = Math.floor(length/4);
    let index    = 0;
    while(index < length){
        let temp    = arr[index];
        if(num < temp){
            //search left
            index = index - 1;
        } else if(num === temp) {
            //matched return this
            return true
        } else {
            // jump eachBlock  
            index = index + eachBlock;
        }
    }
    return false;

} // O(√4)

console.log(JumpSearch(arr, 14))

我在这里尝试在JavaScript中实现JumpSearch。 如果有时,它会无限期地继续运行else块 结果不匹配。

请看看。

1 个答案:

答案 0 :(得分:2)

我认为这是正确的,基本上是从PHP代码改编而成。您实际上可以通过间隔。他们说阵列长度的平方根是最佳的。第一个循环获取间隔,如果num不在间隔中,则返回-1。第二个循环从间隔的开始处开始,使索引从间隔的开始处开始递增1,直到到达间隔的末尾为止,直到到达数组的末尾。似乎可以工作。

arr = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233];

const JumpSearch = (arr, num) => {
  const length = arr.length;
  const interval = 3;
  let current = interval;
  let prev = 0;

  while (arr[Math.min(current, length) - 1] < num) {

    prev = current;
    current += interval;
    if (prev >= length) {
      return -1;
    }
  }
  while (arr[prev] < num) {
    prev++;

    // If we reached next block or end of 
    // array, element is not present. 
    if (prev == Math.min(current, length)) return -1;
  }
  // If element is found 
  if (arr[prev] == num) return prev;
  else return -1;
}

console.log(JumpSearch(arr, 21));