刚才看了《只有10%程序员能正确实现二分查找算法》文章http://news.csdn.net/a/20100423/218099.html,于是忍不住用C#写了个,欢迎查找算法的bug
二分查找可以解决(预排序数组的查找)问题:只要数组中包含T(即要查找的值),那么通过不断缩小包含T的范围,最终就可以找到它。一开始,范围覆盖整个数组。将数组的中间项与T进行比较,可以排除一半元素,范围缩小一半。就这样反复比较,反复缩小范围,最终就会在数组中找到T,或者确定原以为T所在的范围实际为空。对于包含N个元素的表,整个查找过程大约要经过log(2)N次比较。
/// <summary>
/// 二分查找法
/// </summary>
/// <param name="aa"></param>
/// <param name="a"></param>
/// <returns></returns>
public static int GetPosition(int[] aa, int a)
{
int arrLength = aa.Length;
int startPosition = 0;
int endPosition = arrLength - 1;
int middlePosition = endPosition / 2;
if (arrLength>0)
{
return GetValuePosition(aa, a, startPosition, endPosition, middlePosition);
}
return -1;
}
public static int GetValuePosition(int[] aa,int a,int startPosition,int endPosition,int middlePosition)
{
if (a == aa[middlePosition])
{
return middlePosition;
}
if (a > aa[middlePosition]&&endPosition>=startPosition)
{
startPosition = middlePosition + 1;
middlePosition = (endPosition + startPosition) / 2;
return GetValuePosition(aa, a, startPosition, endPosition, middlePosition);
}
else if(a<aa[middlePosition]&&endPosition>=startPosition)
{
endPosition = middlePosition - 1;
middlePosition = (endPosition + startPosition) / 2;
return GetValuePosition(aa, a, startPosition, endPosition, middlePosition);
}
return -1;
}