栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++实现二分查找

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 
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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346832.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号