C++ 二分查找 binary search 模板

本文详细介绍了如何使用C++实现二分查找算法,包括如何在已排序的数组中查找特定值,以及当目标值不存在时返回比目标值小的最后一个最大值。示例代码展示了完整的二分查找函数及其在主函数中的应用。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<memory.h>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>

#define mem(array)  memset((array),0,sizeof((array)))
#define Qsort(array,len,cmp) qsort(array,len,sizeof(array[0]),cmp)

#define inf 0x7fffffff
#define MAXN 10+100

using namespace std;


int binarySearch(int* a, int n, int x, int flag = -1)
{   /**
    binarySearch parameter description:
    int * a     a is an array that sorted from small to large
    int n       n is the length of array a
    int x       x is the search object
    int flag    flag is a return sign.
    the function will return the index of the first object that equal to the value of object x if the object exists.
        when the object is not exist, the function will return -1 while flag is -1,
        or return the index of the last maximal object that less than 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值