## 写了二分查找算法，欢迎查找算法bug

/// <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;

}

posted on 2010-04-24 11:26  边写边唱  阅读(521)  评论(1编辑  收藏  举报