二分法查找实现(递归与非递归)

#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;
}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值