JavaScriptはバイナリ検索を実装します

アイデア

  1. 配列の中央の要素から開始して、中央の要素がターゲット値である場合、検索は終了します。
  2. 目標値である場合より大きく又はより少ない中間要素、バイナリ検索が実行され、アレイの半分にあるより大きい又はより小さい中間要素

二分探索の前提条件:配列は順序付けられています

時間計算量:O(logN)

成し遂げる

既存の順序付き配列[3, 4, 5, 6, 7, 9, 12, 15]、二分探索12

Array.prototype.binarySearch = function(item) {
    
    
    let low = 0;
    let high = this.length - 1;
    while (low <= high) {
    
    
        const mid = Math.floor((low + high) / 2);
        const element = this[mid];
        if (element > item) {
    
    
            high = mid - 1;
        } else if (element < item) {
    
    
            low = mid + 1;
        } else {
    
    
            return mid;
        }
    }
    return -1;
};

const res = [3, 4, 5, 6, 7, 9, 12, 15].binarySearch(12);
console.log(res);

結果:

おすすめ

転載: blog.csdn.net/Jack_lzx/article/details/114998401