class Program { static void Main(string[] args) { Console.WriteLine("请输入一个正序排列的整数数组,用空格分割,最后按回车键结束输入:"); string[] ValueStr = Console.ReadLine().Split(' '); Console.WriteLine("请输入要查询的数值:"); int value = int.Parse(Console.ReadLine().Trim()); int[] Items = new int[ValueStr.Length]; for (int i = 0; i < ValueStr.Length; i++) { Items[i] = int.Parse(ValueStr[i].Trim()); } Console.WriteLine("你要查询数值的位置为:" + binarySearch(Items, value).ToString()); Console.ReadLine(); } private static int binarySearch(int[] Items, int value) { if(Items.Length==1) { return 0; } int StartIndex = 0; int EndIndex = Items.Length - 1; int MiddleIndex = (EndIndex + StartIndex) / 2 ; while (Items[MiddleIndex] != value) { if (Items[MiddleIndex] > value) { EndIndex = MiddleIndex - 1; MiddleIndex = (EndIndex + StartIndex) / 2; } else { StartIndex = MiddleIndex + 1; MiddleIndex = (EndIndex + StartIndex) / 2; } } return MiddleIndex; } }
来源:https://www.cnblogs.com/shuwang/archive/2010/04/22/1718108.html