class Program
{
///
/// 二分法查找,递归方法实现,二分查找的条件是原数组有序
/// 没有找到,返回-1;找到了,则返回索引
///
///
/// 最小
/// 最大
/// 需要找的值
///
private static int BinarySearchRecursive(int[] arr, int low, int height, int value)
{
if (arr == null || arr.Length == 0 || low >height)
{
return -1;
}
int hi = height;
int lowValue = arr[low];
int heightValue = arr[hi];
if (lowValue > value || value > heightValue)
{
return -1;
}
int mid;
if (low <= hi)
{
//mid = (low + hi) / 2;
mid = (low + hi) >>1;
int item = arr[mid];
if (item == value)
{
return mid;
}
else if (item > value)//item=3(如果value=2)
{
return BinarySearchRecursive(arr, low, mid, value);//
}
else
{
return BinarySearchRecursive(arr, mid + 1, hi, value);
}
}
return -1;
}
///
/// 插值查找,是对二分法查找的优化
/// 二分法: mid = low + 1/2 (high - low)
/// 插值查找:mid = low + ((point-array[low])/(array[high]-array[low]))(high-low)
/// 插值优化了mid,使之更接近查找数值在有序序列的实际位置
///
///
///
///
///
///
private static int InterpolationSearch(int[] arr, int low, int height, int value)
{
if (arr == null || arr.Length == 0 || low > height)
{
return -1;
}
int hi = height;
int lowValue = arr[low];
int heightValue = arr[hi];
if (lowValue > value || value > heightValue)
{
return -1;
}
int mid;
while (low <= hi)
{
mid = (low + hi) >> 1;//low + ((value - lowValue) / (heightValue - lowValue)) * (hi - low);
int item = arr[mid];//中间
if (item == value)
{
return mid;
}
else if (item > value)
{
hi = mid - 1;
}
else
{
low = mid + 1;
}
}
return -1;
}
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
//int index = BinarySearchRecursive(arr,0,arr.Length-1,7);
int index= InterpolationSearch(arr,0,arr.Length-1,8);
Console.WriteLine(index);
Console.ReadKey();
}
}
二分查找
最新推荐文章于 2020-03-05 16:40:28 发布