using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BinarySearch
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 3, 4, 5, 7, 8, 10, 13, 14, 16 };
int target = 10;
Console.WriteLine("The index of target item {0} in array is: {1}", target, BinarySearch(array, target));
Console.ReadKey();
}
private static int BinarySearch(int[] array, int target)
{
int left = 0;
int right = array.Length - 1;
// Check if the first element is the target value
if (target == array[0]) return 0;
// Check if the last element is the target value
else if (target == array[array.Length - 1]) return array.Length - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (target == array[mid]) return mid;
if (target > array[mid]) left = mid + 1;
else right = mid - 1;
}
return -1;
}
}
}
二分查找
最新推荐文章于 2013-07-11 23:05:56 发布