非递归写法:
public static int search(int left, int right, int[] array, int key) { int mid = (left + right) / 2; //不在当前搜索集里面 if (key < array[0] || key > array[array.Length - 1]) { return -1; } while (left <= right) { if (array[mid] == key) { return mid; } else if (array[mid] > key) { right = mid - 1; } else { left = mid + 1; } } return -1; }
递归写法:
public static int search(int left, int right, int[] array, int key) { int mid = (left + right) / 2; //不在当前搜索集里面 if (key < array[0] || key > array[array.Length - 1]) { return -1; } while (left <= right) { if (array[mid] == key) { return mid; } else if (array[mid] > key) { return search(left,mid-1,array,key); } else { return search(mid+1,right,array,key); } } return -1; }
Main函数:
public static void Main() { int[] array = { 10, 14, 16, 18, 25, 30, 45, 65, 76, 81, 90, 102, 156 }; foreach(int a in array) { Console.Write(a+" "); } Console.WriteLine(); Console.WriteLine("查找10000:"+search(1,array.Length,array,10000)); Console.WriteLine("查找5:" + search(1,array.Length,array, 5)); Console.WriteLine("查找18:" + search(1, array.Length , array, 18)); Console.ReadKey(); }