How to implement binary search in JavaScript

后端 未结 4 1530
醉梦人生
醉梦人生 2020-12-21 15:36

https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/p/challenge-binary-search

I was following the pseudo code to implement algorithm on t

4条回答
  •  不知归路
    2020-12-21 15:43

    If anyone is still looking for the answer, you needed to make it (max >= min)

    while (max >= min) {
     guess = Math.floor((max + min) / 2);
     if (array[guess] === targetValue) {
         return guess;
     }
     else if (array[guess] < targetValue) {
         min = guess + 1;
     }
    else {
        max = guess - 1;
        }
    }
    return -1;
    

提交回复
热议问题