算法练习二:二分查找
static void Main(string[] args)
{
int[] a=new int[] {1,3,58,654,7,9,11,18,17};
int c = Serarch(a, 9);
Console.WriteLine(c);
Console.ReadLine();
Console.Read();
}
static int Serarch(int[] a, int b)
{
int low = 0;
int high = a.Length - 1;
while(low<=high)
{
if (b < a[(high + low )/ 2])
{
high = (high + low) / 2;
}
else if (b >a[(high + low) / 2])
{
low = ((high + low)/ 2)+1;
}
else if (b ==a[(high + low )/ 2])
{
return ((high + low )/ 2)+1;
}
}
return -1;
}
posted on 2009-04-02 15:40 Love Fendi 阅读(153) 评论(0) 编辑 收藏 举报