溫馨提示×

c++二分查找算法代碼怎么寫

c++
小億
161
2024-06-07 09:30:20
欄目: 編程語言

下面是一個示例代碼實現C++中的二分查找算法:

#include <vector>
#include <iostream>

int binarySearch(std::vector<int>& arr, int target) {
    int left = 0;
    int right = arr.size() - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1;
}

int main() {
    std::vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15};
    int target = 9;
    
    int result = binarySearch(arr, target);
    
    if (result != -1) {
        std::cout << "Element found at index: " << result << std::endl;
    } else {
        std::cout << "Element not found in the array" << std::endl;
    }
    
    return 0;
}

在這個示例代碼中,binarySearch函數接受一個已排序的整數數組和一個目標值作為參數,然后使用二分查找算法在數組中查找目標值。如果找到目標值,則返回該值在數組中的索引,否則返回-1。在main函數中,我們創建了一個已排序的整數數組并調用binarySearch函數來查找目標值9。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女