二进制搜索输出

时间:2019-05-15 21:10:45

标签: javascript

因此,我正在进行一些二进制搜索,试图再次查找数字是否为平方,并且我不完全知道如果“找到”不等于true时如何显示输出

我尝试将其放在while循环中,它给了我一个输出,但它不断地反复循环“您的数字不是平方”。但是,如果我把它放在循环之外,我将一无所获

     //perform Binary search 
  right = SIZE;
  left = 0;
  found = false;

  while (left <= right && (!found)) {
  index = Math.floor((left + right) / 2);

  if (numberArray[index] == searchNumber) {

    found = true;
    document.write("Your number is a square!");

    if (numberArray[index] != searchNumber) {
      found != true;
      document.write("Your number is not a square")
    }

  }

  //output
  index++;

  //print message not true
  if (numberArray[index] > searchNumber) {
    right = index - 1;

  } else {
    left = index + 1;
  }
}

预期结果是使程序使用二进制搜索找出数字是否为平方,如果不是则为输出

1 个答案:

答案 0 :(得分:0)

这里的问题是您的第二条if语句将永远不会运行,因为它在第一个if中是相反的比较。

例如,对于相同的indexsearchNumber,永远不会发生if (numberArray[index] == searchNumber)if (numberArray[index] != searchNumber) {都为true

从第一个if中移出第二个if。由于您的第二个if与第一个else相反,您可以将其放在found != true;子句中(杰克在说什么)

另外found = false应该是//perform Binary search right = SIZE; left = 0; found = false; while (left <= right && (!found)) { index = Math.floor((left + right) / 2); if (numberArray[index] == searchNumber) { found = true; document.write("Your number is a square!"); } else { found = false; document.write("Your number is not a square") } //output index++; //print message not true if (numberArray[index] > searchNumber) { right = index - 1; } else { left = index + 1; } }

key