using System;
using System.Collections.Generic;
namespace TestCSharp
{
class Program
{
static void Main(string[] args)
{
int[] list = new int[] { 1, 9, 10, 24, 29, 60 };
Console.WriteLine(BinarySearch(list, 11));
Console.ReadKey();
}
public static int BinarySearch(int[] list, int targetValue)
{
int midIndex = 0;
int startIndex = 0;
int endIndex = list.Length - 1;
while (startIndex <= endIndex)
{
if (startIndex == endIndex)
{
midIndex = startIndex;
if (list[midIndex] == targetValue)
{
return startIndex;
}
return -1;
}
midIndex = (int)(startIndex + ((targetValue - list[startIndex]) / (float)(list[endIndex] - list[startIndex])) * (endIndex - startIndex));
//Console.WriteLine(string.Format("startIndex={0}, endIndex={1}, minIndex={2}", startIndex, endIndex, midIndex));
if (midIndex < startIndex || midIndex > endIndex)
{
if (list[midIndex] == targetValue)
{
return midIndex;
}
return -1;
}
if (list[midIndex] > targetValue)
{
endIndex = midIndex - 1;
}
else if (list[midIndex] < targetValue)
{
startIndex = midIndex + 1;
}
else
{
return midIndex;
}
}
return -1;
}
}
}