原理很简单,二叉树的原理
public static void erfen(int[] array, int val) { int leftIndex = 0;//查找起始下标 int rightIndex = array.Length - 1;//数组终点下标,即最坏情况 int currentIndex = 0;//当前查找的下标 Array.Sort(array);//先升序排序 //等起始<=终点时,可以继续查找 while (leftIndex <= rightIndex) { currentIndex = (leftIndex + rightIndex) / 2; if (array[currentIndex] < val) { leftIndex = currentIndex+1; Console.WriteLine(string.Format("没找到!从下标{0}开始往后找!",currentIndex+1)); } else if (array[currentIndex] > val) { rightIndex = currentIndex-1; Console.WriteLine(string.Format("没找到!从下标{0}开始往前找!",currentIndex-1)); } else { Console.WriteLine(string.Format("找到了!{0}在数组中的下标是{1}", val, currentIndex)); break; } } }