JavaScript 中的二分查詢程式


建立一個函式,例如 binarySearch(),其中包含 4 個引數 -

  • 一個已排序的 Number / String 字面陣列
  • 陣列的起始索引 (0)
  • 陣列的結束索引 (length - 1)
  • 要搜尋的數字

如果數字存在於陣列中,則返回該數字的索引,否則返回 -1。以下是完整程式碼 -

示例

const arr = [2,4,6,6,8,8,9,10,13,15,17,21,24,26,28,36,58,78,90];
//binary search function
//returns the element index if found otherwise -1
const binarySearch = (arr, start, end, num) => {
   const mid = start + Math.floor((end - start)/2);
   if(start <= end){
      if(arr[mid] === num){
         return mid;
      }
      if(num < arr[mid]){
         return binarySearch(arr, start, mid-1, num);
      }
      if(num > arr[mid]){
         return binarySearch(arr, mid+1, end, num);
      }
   }
   return -1;
};
console.log(binarySearch(arr, 0, arr.length-1, 13));
console.log(binarySearch(arr, 0, arr.length-1, 11));

輸出

此程式碼在控制檯中的輸出為 -

8
-1

更新於: 20-Aug-2020

655 次瀏覽

開啟您的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.