二分查找(针对有序数组)

算法代码


   

int Binary_search(DateType *a,DateType K,const DateType n)
{
	int beg = 1,end = n;
	mid = beg + (end - beg)/2; //mid不赋值为"(beg+end)/2",防止开大数组越界
	while((mid != end) && (a[mid] != K))
	{
		if(a[mid] < K)
			beg = mid + 1;
		else
			end = mid;
		mid = beg + (end -beg)/2;				
	} 
	if(a[mid] == K)
		return mid;
	else
		return -1;
}

最坏情况是a[1] or a[n] = k,假设需要二分m次,则有:
n/2 n/4 n/8 ... n/(2^m) = 1;
得2^m = n,所以时间复杂度为O(lg(n))

 

图解


 

 

  

 (图片来源于CSDN博主皓皓松

posted @ 2017-09-10 20:25  bw98  阅读(478)  评论(0编辑  收藏  举报