C++实现二分查找

问题描述:
给定一递增有序数组a[0,1,…,n-1],请在数组中搜索给定元素。 搜索过程中请使用mid=(low+high)/2。搜索成功输出success及父亲,否则输出not found及父亲。

输入示例:
2
7 10 1 3 5 7 9 11 13
7 10 2 4 6 8 10 12 14

输出示例:
not found, father is 9
success, father is 12

代码:

//  Created by 胡昱 on 2018/10/8.
//  Copyright © 2018年 胡昱. All rights reserved.

#include <iostream>
using namespace std;

// 存储结果的结构体
struct Result{
    bool isSuccess = false;
    int father = 0;
};

// 二分查找函数
Result BinarySearch(int* a, const int n, const int x)
{
    // 初始化结果存储结构
    Result result;
    
    // 在数组 a[0], ..., a[n-1] 中寻找 x
    int left = 0, right = n-1, middle = (left + right) / 2;
    while(left <= right)
    {
        if(x < a[middle])
        {
            right = middle - 1;
        }
        else if(x > a[middle])
        {
            left = middle + 1;
        }
        else
        {
            result.isSuccess = true;
            return result;
        }
        
        // 寻找新的中线
        result.father = a[middle];
        middle = (left + right) / 2;
    }
    
    // 没有找到
    result.isSuccess = false;
    return result;
}

int main(int argc, const char * argv[])
{
    // 共有m个问题
    int m;
    cin >> m;
    while((m--) > 0) {
        
        // 输入数组以及要寻找的数
        int n;
        cin >> n;
        int x;
        cin >> x;
        int * array = new int[n];
        for(int i = 0; i < n; ++i)
        {
            cin >> array[i];
        }
        
        
        // 二分查找并输出结果
        Result result = BinarySearch(array, n, x);
        if(result.isSuccess) {
            cout << "success, father is " << result.father << endl;
        }
        else {
            cout << "not found, father is " << result.father << endl;
        }
        
        // 释放资源
        delete [] array;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值