记得很多年前看的数据结构教程,上边也讲到二分查找算法,但好像用的是递归,最近项目需要,试着清理了一下排递归的写法,直接上代码:
static void Main(string[] args)
{
int len = 100000;
var arr = new int[len];
for (var i=0; i<arr.Length; i++)
{
arr[i] = i + 1;
}
int fdv = 38902;
int fdex = -1;
int a = 0;
int b = arr.Length - 1;
int times = 0;
while (true)
{
++times;
int mid = (int)(b - a) / 2 + a;
int v = arr[mid];
if (v == fdv)
{
fdex = mid;
break;
}
if (fdv > v)
{
a = mid+1;
}
else
{
b = mid-1;
}
}
Console.Write(fdex + ",\ttimes:" + times);
Console.ReadLine();
}