二分查找

来源:互联网 发布:软件测试工具下载 编辑:程序博客网 时间:2024/05/24 05:43
//============================================================================
// Name        : C++Study.cpp
// Author      : pan
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================


#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <stack>
#include <assert.h>
#include <string.h>
using namespace std;


int bin_find(int a[], int n, int c) {


int front = 0, tail = n, middle;
while (front <= tail) {
middle = (front+tail) / 2;
if (a[middle] == c) {
return middle;
}
if (a[middle] < c) {
front = middle;
}
if (a[middle] > c) {
tail = middle;
}
}


return -1;
}


int main() {


int a[5] = { 1, 2, 3, 4, 5 };
int res = bin_find(a, 5, 3);
cout << res;


return 0;

}

//尾递归



int binfind(int a[],int data,int start,int send)
{
    if(start>send){
       return -1;
    }
    int middle=(start+send)/2;
    if(a[middle]==data){
        return middle;
    }else if(a[middle]>data){
        return binfind(a,data,start,middle-1);
    }else{
        return binfind(a,data,middle+1,send);
    }
}
int main()
{
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    int res=binfind(a,1,0,9);
    cout << res << endl;
    return 0;
}





0 0
原创粉丝点击