陣列中的二分搜

常見

實作

範例程式碼

#include <bits/stdc++.h>
using namespace std;
int main() {
    int arr[10] = {1, 5, 9, 17, 21, 28, 33, 39, 41, 48};
    int left = -1, right = 10;
    int ans = 28;
    bool found = false;
    // ans 是要搜尋的數字 left 是左界 right 是右界
    while (left + 1 < right) {
        int mid = (left + right) / 2;
        // mid 左界和右界的中點
        if (ans == arr[mid]) {
            // 找到答案了!
            cout << "answer is " << arr[mid];
            found = true;
            break;
        }
        else if (ans < arr[mid]) {
            // 答案比當前中點還要大
            right = mid;
        }
        else {
            // 答案比當前中點還要小
            left = mid;
        }
    }
    if (found == false) {
        // 陣列中沒有想搜尋的答案
        cout << "answer not found in array";
    }
}