二分法查找实现(递归与非递归)
程序员文章站
2024-03-17 23:05:52
...
#include<iostream>
#include<algorithm>
#include<ctime>
#define N 10
using namespace std;
/*顺序查找函数内容*/
int find (int *array, int target){
for(int i=0;i<N;i++){
if(target==array[i])
return i;
}
return -1;
}
/*非递归二分查找*/
int BinarySearch(int *array, int size, int target)
{
if(array==NULL||size==0)
return -1;
int low=0,high=size;
int mid=0;
while(low<=high){
mid=(low+high)/2;
if(array[mid]>target)
low=mid+1;
else if(array[mid]<target)
high=mid-1;
else
return mid;
}
return -1;
}
/*递归二分查询 lg(N)*/
int BinarySearchRecursive(int *array, int low, int high, int target)
{
if ( low > high )
return -1;
int mid = ( low + high )/2;
if (array[mid] == target )
return mid;
else if ( array[mid] < target )
return BinarySearchRecursive(array, mid+1, high, target);
else
return BinarySearchRecursive(array, low, mid-1, target);
}
/*打印输出数组内容*/
void print(int *array, int length){
for(int i=0;i<length-1;i++)
cout<<array[i]<<" ";
cout<<array[length-1]<<endl;
}
/*用于sort函数调用*/
bool compare(int a, int b){
return a>b;
}
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned int)time(NULL));
int *array=new int[N];
for(int i=0;i<N;i++)
array[i]=rand()%100;
print(array,N);
int result=find (array,array[3]);
cout<<result<<endl;
sort(array,array+N);
print(array,N);
cout<<BinarySearchRecursive(array,0, N, array[3])<<endl;
sort(array,array+N,compare);
print(array,N);
cout<<BinarySearch(array,N,array[9])<<endl;
delete []array;
return 0;
}
上一篇: 面试算法摘要(Ⅱ)
下一篇: lua中ipairs 和pairs的区别