二分查找算法(C++)

C++二分查找算法

原理如下图:

这里写图片描述
该算法只针对有序列表才有意义。

#include <iostream>
using namespace std;
//二分搜索算法,折半查找
//二分查找要求被查找的数组的元素是按照有序的顺序排列的
int main()
{
    int array[100];
    //数组的大小
    int size = 0;
    cout << "输入需要创建的数组的元素个数:" << endl;
    cin >> size;
    //向数组中按序添加元素
    for (auto i = 0; i < size; i++)
    {
        array[i] = i;
    }
    //输入要在数组中查找的书
    int checkElement;
    cin >> checkElement;
    //数组的第一个元素
    int headIndex = 0;
    //数组的最后一个元素
    int tailIndex = (size - 1);
    if (checkElement<headIndex || checkElement>tailIndex)
    {
        cout << "你输入的数字不在当前搜索的范围内" << endl;
        return 0;
    }
    //对数组进行遍历,找出对应数字在数组中的下标索引
    int centerIndex = (headIndex + tailIndex) / 2;
    //如果中间索引的值大于要搜索的值,则在左边进行查找
    while (headIndex <= tailIndex)
    {
        if (array[centerIndex] < checkElement)
        {
            headIndex = centerIndex + 1;
            cout << "查找中----右边" << endl;
        }
        else if (array[centerIndex] == checkElement)
        {
            cout << "查找到了当前的数字" <<array[centerIndex]<<endl;
            break;
        }
        else
        {
            tailIndex = centerIndex - 1;
            cout << "查找中----左边" << endl;
        }
        centerIndex = (headIndex + tailIndex) / 2;
    }
    if (headIndex > tailIndex)
    {
        cout << "当前数组中没有查找到你想要的数字" << endl;
    }
    return 0;
}

注意输入的数组的大小不要大于初始给定的数组的长度。

欢迎关注公众号,每周分享Unity3D、C++、C#、数据结构和算法学习的相关知识。

码码小虫

### 关于C++实现二分查找算法 #### 原理概述 二分查找是一种高效的搜索算法,适用于已排序的数据集合。其基本思想是通过不断缩小搜索范围来快速定位目标值。每次比较中间位置的元素与目标值的关系后,可以排除一半的候选区域[^2]。 以下是基于上述参考资料整理的一个完整的C++实现版本: ```cpp #include <iostream> using namespace std; // 定义二分查找函数 int binarySearch(int arr[], int size, int target) { int left = 0; int right = 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; // 如果未找到目标值,则返回-1 } int main() { int arr[] = {1, 3, 5, 7, 9, 11}; // 已排序数组 int size = sizeof(arr) / sizeof(arr[0]); int target = 7; int result = binarySearch(arr, size, target); if (result != -1) { cout << "Element found at index: " << result << endl; } else { cout << "Element not found!" << endl; } return 0; } ``` 此代码实现了标准的二分查找逻辑,并考虑了可能的边界条件以及防止溢出的情况[^4]。 --- #### 特殊情况处理 除了基础的二分查找外,在某些场景下还需要扩展功能,比如寻找某个值的第一个或最后一个出现位置。下面是一个用于寻找右侧边界的例子: ```cpp template<typename T> int findRightBound(T arr[], int size, T value) { int left = 0, right = size - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] <= value) { if (mid == size - 1 || arr[mid + 1] > value) { return mid; // 返回右侧边界位置 } else { left = mid + 1; // 继续向右移动 } } else { right = mid - 1; // 向左调整区间 } } return -1; // 若不存在满足条件的位置则返回-1 } ``` 该方法可用于解决更复杂的实际问题,例如统计某范围内符合条件的元素数量。 --- #### 使用递归的方式实现 如果希望采用递归来完成同样的任务,也可以按照如下方式进行设计: ```cpp int recursiveBinarySearch(int arr[], int left, int right, int target) { if (left > right) return -1; int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { return recursiveBinarySearch(arr, mid + 1, right, target); } else { return recursiveBinarySearch(arr, left, mid - 1, target); } } int main() { int arr[] = {1, 3, 5, 7, 9, 11}; int size = sizeof(arr) / sizeof(arr[0]); int target = 7; int result = recursiveBinarySearch(arr, 0, size - 1, target); if (result != -1) { cout << "Element found at index: " << result << endl; } else { cout << "Element not found!" << endl; } return 0; } ``` 这种方法虽然直观易懂,但在极端情况下可能会因为栈空间不足而导致性能下降[^3]。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值