//测试代码
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;
}
}
}
原文:https://www.cnblogs.com/LZHOO97/p/12057517.html