sicily Binary Search 二分查找

来源:互联网 发布:辽宁省软件协会 编辑:程序博客网 时间:2024/06/07 18:24

题目

Description

实现二分查找函数,函数接口如下。

/* size为数组s的实际大小。
假定s非递减有序,如果s中存在值为target的元素,
则返回最后一次出现的位序号,否则返回-1表示不存在。
位序号从0开始计。*/
int binSearch(const int s[], const int size, const int target)
{
// 请将实现代码添加在这里
}

提交时只需提交上述函数,不要提交main()函数。

调用例子:

int s[8] = {0,1,1,3,3,3,6,6};

cout << binSearch(s,8,3) << endl; //输出5

cout << binSearch(s,8,4) << endl; //输出-1

Hint

不允许使用STL库里面的相关函数和库(否则可能会出现编译错误)

包括iostream, map, vector, set, algorithm, queue等

思考

二分查找基本思路
1、对比中间点的值与target的值的大小
2、折半继续重复第一步

参考:你真的会二分查找吗?

代码

#include <iostream>using namespace std;int binSearch(const int s[], const int size, const int target) {    int lhs, rhs, mid;    lhs = 0;    rhs = size - 1;    while (lhs < rhs) {        mid = lhs + ((rhs-lhs)>>1); //  除二,这样除避免越界        if (s[mid] > target) {            rhs = mid - 1;  //  必须-1        } else {            if (s[mid + 1] != target && s[mid] == target) return mid;   //判断后续有无            lhs = mid + 1;  // 必须+1        }    }    if (s[rhs] != target) return -1;    return rhs;}int main(int argc, const char * argv[]) {    // insert code here...    int s[8] = {0,1,1,3,4,5,6,6};    cout << binSearch(s,8,3) << endl;  //输出5    cout << binSearch(s,8,2) << endl;  //输出-1    return 0;}
0 0
原创粉丝点击