/// <summary> /// 二分查找 /// </summary> /// <param name="arr"></param> /// <param name="low">开始索引 0</param> /// <param name="high">结束索引 </param> /// <param name="key">要查找的对象</param> /// <returns></returns> public static int BinarySearch(int[] arr, int low, int high, int key) { int mid = (low + high) / 2; if (low > high) return -1; else { if (arr[mid] == key) return mid; else if (arr[mid] > key) return BinarySearch(arr, low, mid - 1, key); else return BinarySearch(arr, mid + 1, high, key); } }
int[] y = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13 }; int rr = BinarySearch(y, 0, y.Length - 1, 13); Console.Write(rr); //12