C语言实现二分查找

二分查找的时间复杂度为 O(logn)

代码如下:

#include

int BinarySearch(int right,int a[],int k,int left);

int main()
{
	int a[7]={1,5,7,9,13,45,79};
	int k;
	
	scanf("%d",&k);
	int position=BinarySearch(0,a,k,6);
	
	if(position>=0)
		printf("%d",position);
	else
		printf("Not found.");	

        return 0;
} 

int BinarySearch(int right,int a[],int k,int left)
{
	//递归 
	/*int middle;
	
	if(right>left)
		return -1;
	else
	{
		middle=(right+left)/2;
		if(a[middle] == k)
			return middle;
		else if(a[middle] > k)
			return BinarySearch(right,a,k,middle-1);
		else
			return BinarySearch(middle+1,a,k,left);
	}*/
	
	
	//非递归
	int middle;
	
	while(right<=left)
	{
		middle=(right+left)/2;
		if(a[middle] == k)
			return middle;
		else if(a[middle] > k)
			left=middle-1;
		else
			right=middle+1;	
	} 
	
	if(right>left)
		return -1;
}

 

你可能感兴趣的:(C)