以下是一个简单的折半查找算法的C++实现代码:

#include <iostream>
using namespace std;

int binarySearch(int arr[], int left, int right, int target) {
    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() {
    int arr[] = { 1, 3, 5, 7, 9, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 5;
    int index = binarySearch(arr, 0, n - 1, target);
    if (index == -1)
        cout << "Element not found in array";
    else
        cout << "Element found at index " << index;
    return 0;
}

这个程序首先定义了一个binarySearch函数,该函数接受四个参数:一个整数数组、查找范围的左边界、查找范围的右边界和要查找的目标元素。该函数使用while循环来不断缩小查找范围,直到找到目标元素或查找范围为空为止。在每次循环迭代中,函数首先计算中间元素的索引,然后将目标元素与中间元素进行比较。如果目标元素等于中间元素,则找到了目标元素并返回其索引。如果目标元素小于中间元素,则在左侧查找。否则,在右侧查找。

在主函数中,我们定义了一个有序数组,并调用binarySearch函数来查找目标元素。如果找到了目标元素,则输出其索引。否则,输出“Element not found in array”。

用c++使用折半查找法,在给定的有序数组中查找输入的数据

原文地址: https://www.cveoy.top/t/topic/vlG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录