//二分查找
//查找一个排序后的数组Arr中是否含有元素Key
//若有,则返回Key在数组中的下标;若无,则返回-1
#include "stdafx.h"
//这个函数有问题,用主函数现在的设置做测试,发现会死循环
//最后High=7,Low=6,Mid=6
//而(Key > Arr[MidIndex])永久成立,因为Low==Mid,所以下标不会被修正
//事实上,这个Key不存在于数组中
int BinarySearchInSortedArr_error(const int* Arr, const int Len, int Key)
{
int Low = 0;
int High = Len - 1;
int MidIndex = (High + Low) / 2;
while (Low < High)
{
if (Key == Arr[MidIndex])
{
return MidIndex;
}
if (Key > Arr[MidIndex])
{
Low = MidIndex;
}
else
{
High = MidIndex;
}
MidIndex = (High + Low) / 2;
}
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int Arr[10] = {-5,-2,-1,0,2,4,5,8,10,15};
int SearchResult = 0;
int x = 7;
SearchResult = BinarySearchInSortedArr_error(Arr,10,x);
if (-1 != SearchResult)
{
if (Arr[SearchResult] == x)
{
printf("Successfully!");
}
}
return 0;
}
//二分查找
//查找一个排序后的数组Arr中是否含有元素Key
//若有,则返回Key在数组中的下标;若无,则返回-1
#include "stdafx.h"
//这个函数是正确的
//错误的函数(BinarySearchInSortedArr-error)对于Low和High的修正有漏洞
//因为当(Key > Arr[MidIndex])成立时,已经确定Key比Arr[MidIndex]大,则搜索应该从Mid之后开始
int BinarySearchInSortedArr(const int* Arr, const int Len, int Key)
{
int Low = 0;
int High = Len - 1;
int MidIndex = (High + Low) / 2;//注意取中值是High+Low,不是减
while (Low <= High) //等于的情况也要考虑
{
if (Key == Arr[MidIndex])
{
return MidIndex;
}
if (Key > Arr[MidIndex])
{
Low = MidIndex + 1;//注意,Low改变的时候要Mid+1
}
else
{
High = MidIndex - 1;//而High改变的时候要Mid-1,这样才可能出现Low>High终止循环
}
MidIndex = (High + Low) / 2;
}
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int Arr[10] = {-5,-2,-1,0,2,4,5,8,10,15};
int SearchResult = 0;
int x = 7;
SearchResult = BinarySearchInSortedArr(Arr,10,x);
if (-1 != SearchResult)
{
if (Arr[SearchResult] == x)
{
printf("Successfully!");
}
}
return 0;
}