二分搜索-C#

static void Main(string[] args)
{
  int[] array = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
  int result = BinarySearch(array, 55);
  Console.WriteLine(result);
}

只能查找有序的线性表
static int BinarySearch(int[] array, int key)
{
  int left = 0;
  int right = array.Length - 1;
  while (left <= right)
  {
    if (key == array[left])
      return array[left];
    if (key == array[right])
      return array[right];

    int middle = (left + right) / 2;
    if (key == array[middle])
      return array[middle];
    else if (key > array[middle])
      left = middle + 1;
    else
      right = middle - 1;
  }
  return -1;
}

二分搜索-C#

上一篇:C#委托的学习


下一篇:Delphi中使用ISuperObject解析Json数据