欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现递归版二分搜索算法

程序员文章站 2022-07-26 11:36:37
无聊撸了一个,没啥技术含量,别吐槽。。 include using namespace std; int BinarySearch(int nums,int key,int len); int search(int nums,int key,int L,int R); int main() { in ......

无聊撸了一个,没啥技术含量,别吐槽。。

#include <iostream>
using namespace std;
int BinarySearch(int* nums,int key,int len);
int search(int* nums,int key,int L,int R);

int main()
{
    int *nums;
    int length;
    int keyNum;
    cout<<"请输入你希望的数字个数:"<<endl;
    cin>>length;
    nums = new int[length];
    cout<<"请输入"<<length<<"个数:"<<endl;
    for(int i=0;i<length;i++)
        scanf("%d",&nums[i]);
    cout<<"输入你想找的数字::"<<endl;
    while(cin>>keyNum){
        int result = BinarySearch(nums,keyNum,length);
        if(!(result==-1))
            cout<<"Position in array is: "<<result<<"\n"<<endl;
        else
            cout<<"Failed!"<<endl;
        delete[] nums;
        cout<<"请输入你希望的数字个数:"<<endl;
        cin>>length;
        nums = new int[length];
        cout<<"请输入"<<length<<"个数:"<<endl;
        for(int i=0;i<length;i++)
            scanf("%d",&nums[i]);
        cout<<"输入你想找的数字::"<<endl;
    }
    return 0;
}

int BinarySearch(int* nums,int key,int len){ //仅作为用户入口
    return search(nums,key,0,len);
}

int search(int* nums,int key,int L,int R){
    int mid = (L+R)/2;
    if(nums[mid]==key) return mid;   //递归基
    if(nums[mid]>key)
        return search(nums,key,L,mid-1);
    else if(nums[mid]<key)
        return search(nums,key,mid+1,R);
    return -1;   //如果失败了返回-1
}

OVER