C# 改进版二分查找法
public static int BinarySearchRecursion(IList<int> arry, ref int value) { //如果传入的数组为空或者数组长度<=0那么就返回-1。防御性编程 if (arry == null || arry.Count <= 0) return -1; int start = 0; int end = arry.Count - 1; return BinarySearchRecursion(arry, ref value, ref start, ref end); } private static int BinarySearchRecursion(IList<int> arry, ref int value, ref int start, ref int end) { if (start > end) return -1; int mid = start + (end - start) / 2; if (arry[mid] == value) return mid; else if (value < arry[mid]) { end = mid - 1; return BinarySearchRecursion(arry, ref value, ref start, ref end); } else { start = mid + 1; return BinarySearchRecursion(arry, ref value, ref start, ref end); } }
测试代码
static void Main(string[] args) { Stopwatch watchTemp = new Stopwatch(); //int[] arry = new int[100000]; IList<int> arry = new List<int>(); for (int i = 0; i < 300; i++) { arry.Add(i); } int value = 100; watchTemp.Start(); int index = BinarySearchRecursion(arry, ref value); watchTemp.Stop(); Console.WriteLine(index.ToString() + "-二分时间:" + watchTemp.Elapsed.TotalSeconds.ToString("0.00000")); //watchTemp.Start(); //int index2 = (from p in arry where p == value select p).Count(); //watchTemp.Stop(); //Console.WriteLine(index2.ToString() + "-Linq时间:" + watchTemp.Elapsed.TotalSeconds.ToString("0.00000"));
}
参考自:http://www.cnblogs.com/xwdreamer/archive/2012/05/07/2487246.html