二分探索 に作用する検索テクニックです。 分割統治アプローチ 。ソートされた配列内の要素を検索するために使用されます。線形検索と比較すると、二分探索は時間計算量 O(logN) ではるかに高速ですが、線形検索は時間計算量 O(N) で動作します。
例 :
Input : arr[] = {1, 3, 5, 7, 8, 9}, x = 5 Output : Element found! Input : arr[] = {1, 3, 5, 7, 8, 9}, x = 6 Output : Element not found!> 注記: 配列がソートされていると仮定します。
JavaScript で二分検索を行う方法は次のとおりです。
目次
Javaスタックとは何ですか
再帰的アプローチ:
- 基本状態: 開始インデックスが終了インデックスより大きい場合は、false を返します。
- 中間のインデックスを計算します。
- 中央の要素を数値 x と比較します。等しい場合は true を返します。
- それより大きい場合は、終了インデックス = middle-1 で同じ関数を呼び出し、手順 1 を繰り返します。
- 小さい場合は、開始インデックス = middle+1 で同じ関数を呼び出し、手順 1 を繰り返します。
例: この例は、上で説明したアプローチの使用法を示しています。
JavaScript
文字列検索 - C++
let recursiveFunction =>function> (arr, x, start, end) {> >// Base Condition> >if> (start>終了)>>;> >// Find the middle index> >let mid = Math.floor((start + end) / 2);> >// Compare mid with given key x> >if> (arr[mid] === x)>return> true>;> >// If element at mid is greater than x,> >// search in the left half of mid> >if> (arr[mid]>x)> >return> recursiveFunction(arr, x, start, mid - 1);> >else> >// If element at mid is smaller than x,> >// search in the right half of mid> >return> recursiveFunction(arr, x, mid + 1, end);> }> // Driver code> let arr = [1, 3, 5, 7, 8, 9];> let x = 5;> if> (recursiveFunction(arr, x, 0, arr.length - 1)) {> >console.log(>'Element found!'>);> }> else> { console.log(>'Element not found!'>); }> x = 6;> if> (recursiveFunction(arr, x, 0, arr.length - 1)) {> >console.log(>'Element found!'>);> }> else> { console.log(>'Element not found!'>); }> |
Python // 演算子
>
>出力
Element found! Element not found!>
時間計算量: O(logN)
補助スペース: ○(1)
反復的なアプローチ:
この反復アプローチでは、再帰の代わりに while ループを使用し、ループは基本条件に達するまで実行されます。つまり、start が end よりも大きくなります。
例: この例は、上で説明したアプローチの使用法を示しています。
JavaScript
パンダのイテロウ
// Iterative function to implement Binary Search> let iterativeFunction =>function> (arr, x) {> >let start = 0, end = arr.length - 1;> >// Iterate while start not meets end> >while> (start <= end) {> >// Find the mid index> >let mid = Math.floor((start + end) / 2);> >// If element is present at> >// mid, return True> >if> (arr[mid] === x)>return> true>;> >// Else look in left or> >// right half accordingly> >else> if> (arr[mid] start = mid + 1; else end = mid - 1; } return false; } // Driver code let arr = [1, 3, 5, 7, 8, 9]; let x = 5; if (iterativeFunction(arr, x, 0, arr.length - 1)) { console.log('Element found!'); } else { console.log('Element not found!'); } x = 8; if (iterativeFunction(arr, x, 0, arr.length - 1)) { console.log('Element found!'); } else { console.log('Element not found!'); }> |
tostring Javaメソッド
>
>出力
Element found! Element found!>
時間計算量: O(logN)。
補助スペース: ○(1)