二分搜索程序

二分搜索递归与非递归的写法

#include
using namespace std;
int searchNum(int a[], int m, int n, int num)
{
    int index = (m+n)/2;
   
    if(n       return -1;
    if(a[index]==num)
        return index;
    else if(a[index] > num )
        return searchNum(a, m, index-1,num);
    else if(a[index] < num )
        return searchNum(a, index+1, n,num);
    else
        return -1;
}
int searchNum2(int a[], int m, int n, int num)
{
    int index = -1;
    while(m<=n)
    {            
           index = (m+n)/2;
          
           if(a[index] == num)
               return index;
           else if(a[index] < num)
               m = index +1;
           else if(a[index] > num)
               n = index - 1;
    }

    return index;
}
int main()
{
    int a[10] = {0,1,2,3,4,5,6,7,8,9};
    cout << searchNum2(a,0,9,5) << endl;
    system("pause");
    return 1;
}

转载于:https://www.cnblogs.com/hxf829/archive/2009/07/27/1659785.html

你可能感兴趣的:(二分搜索程序)