用循环和递归实现二分查找

经过验证 

#include <iostream>

#define len 2

int bisectionSearch(int *a, const int &left, const int &right, const int &target)
{
    if (left > right)
        return -1;

    int mid = (left + right) / 2;

    if (a[mid] < target)
        return bisectionSearch(a, mid+1, right, target);
    else if (a[mid] > target)
        return bisectionSearch(a, left, mid-1, target);
    else
        return mid;
}

int loopSearch(int *a, const int &length, const int &target)
{
    int right = length - 1;
    int left = 0;

    int mid;
    
    while (left <= right)
    {
        mid = (left + right) / 2;

        if (target < a[mid])
            right = mid - 1;
        else if (target > a[mid])
            left = mid + 1;
        else
            return mid;
    }

    return -1;
}

int main()
{
    int a[len];
    int right = len - 1;
    int left = 0;

    for (int i = 0; i < len; ++i)
        std::cin >> a[i];

    int x;
    std::cin >> x;

    int index;

    index = loopSearch(a, len, x);
    //index = bisectionSearch(a, left, right, x);
    
    if (-1 != index)
        std::cout << index << std::endl;
    else
        std::cout << "no element matches" << std::endl;

    return 0;
}

 

发布了9 篇原创文章 · 获赞 0 · 访问量 122
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览