二分查找的简单实践

二分法查找,简单的调用索引思路,结构比较清晰吧:

(可以看下代码后的分析)

#include <iostream>
#include <array>
using namespace std;

int binary_search(const array<int, 7>& 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; // 如果没有找到目标值,返回-1
}

int main()
{
    const array<int, 7> arr = {1,5, 7, 9, 11, 13, 15};
    int target = 11;
    int result = binary_search(arr, target);

    if (result != -1)
    {
        cout << "Element found at index: " << result << endl;
    }
    else
    {
        cout << "Element not found in the array" << endl;
    }

    return 0;
}

 

首先,我们定义了一个数组 arr 和它的长度 n。然后,我们实现了一个 binary_search 函数,该函数接受一个数组、数组的长度和一个目标值。

const array<int, 7> arr = {1,5, 7, 9, 11, 13, 15};
    int target = 11;
    int result = binary_search(arr, target);

1>const无关紧要,加不加随你;

2>如果要自定义,稍稍再此处修改即可;

 

在 binary_search 函数中,我们使用两个指针 left 和 right 分别表示数组的左边界和右边界。然后我们使用一个循环来折半查找数组,直到找到目标值或左右边界相遇。

int binary_search(const array<int, 7>& 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; // 如果没有找到目标值,返回-1
}

1> return 返回值可以直接自定义,方便以后的操作;

2>切记,返回的是索引,索引从0开始;

在 main 函数中,我们定义了一个目标值 target 和一个数组 arr,然后调用 binary_search 函数来查找目标值。最后,我们根据查找结果输出相应的信息。

if (result != -1)
    {
        cout << "Element found at index: " << result << endl;
    }
    else
    {
        cout << "Element not found in the array" << endl;
    }

1>return 0;这条语句不写其实也无所谓,在很多编译器上只是警告,return返回值自己定义也完全OK;

2>可以直接定义void取代int,为了避免警告和麻烦。

  • 17
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值