barretlee / algorithms

All algorithms writing with javascript in the book 'Algorithms Fourth Edition'.
MIT License
337 stars 41 forks source link

BinarySearch #1

Open barretlee opened 8 years ago

barretlee commented 8 years ago

/chapter-1-fundamentals/1.1-programming-model/BinarySearch.js

barretlee commented 8 years ago
function BinarySearch(input, key) {
  return indexOf(input, key);

  function indexOf(a, k) {
    var start = 0;
    var end = a.length - 1;
    while(start <= end) {
      var mid = Math.floor((end - start) / 2) + start;
      if(k < a[mid]) {
        end = mid - 1;
      } else if(k > a[mid]) {
        start = mid + 1;
      } else {
        return mid;
      }
    }
    return -1;
  }
}
lessfish commented 8 years ago

小胡子哥习惯在函数声明最后面加个封号么?

barretlee commented 8 years ago

@hanzichi 分号去掉了,不是习惯,可能是复制的时候多写了一个。