static void Main(string[] args) { char[] arr = new[] { 'a', 'b', 'c', 'd', 'e'}; char v = 'd'; var index = BiSearch(arr, 0, 4, v); Console.WriteLine(index); char[] arr2 = new[] { 'b', 'c', 'd', 'e', 'f' }; char v2 = 'a'; var index2 = BiSearch(arr2, 0, 4, v2); Console.WriteLine(index2); Console.Read(); } static int BiSearch(char[] arr, int b, int e, char v) { int minIndex = b, maxIndex = e, midIndex; //循环结束有两种情况: //若minIndex为偶数则minIndex == maxIndex //否则就是minIndex == maxIndex - 1 while (minIndex < maxIndex - 1) { midIndex = minIndex + (maxIndex - minIndex)/2; if (arr[midIndex].CompareTo(v) <= 0) { minIndex = midIndex; } else { //不需要midIndex - 1,防止minIndex == maxIndex maxIndex = midIndex; } } if (arr[maxIndex].CompareTo(v) == 0) { return maxIndex; } else if (arr[minIndex].CompareTo(v) == 0) { return minIndex; } else { return -1; } }