算法篇----二分查找
using System;
namespace NET.MST.Thirtennth.BinarySearch
{
class BinarySearch
{
/// <summary>
/// 测试二分查找算法
/// </summary>
static void Main(string[] args)
{
//测试序列,实际系统中,如果得到乱序序列则应该先使用排序算法进行排序
int[] data = new int[] { 0, 2, 3, 4, 6, 7, 8, 10 };
Console.WriteLine("测试序列为");
for (int i = 0; i < data.Length; i++)
Console.Write("{0},", data[i]);
Console.Write("\r\n");
Console.WriteLine("查找元素{0},查找结果为:{1}", 3, Search(data, 3));
Console.WriteLine("查找元素{0},查找结果为:{1}", 0, Search(data, 0));
Console.WriteLine("查找元素{0},查找结果为:{1}", 10, Search(data, 10));
Console.WriteLine("查找元素{0},查找结果为:{1}", 9, Search(data, 9));
Console.Read();
}
/// <summary>
/// 二分查找算法
/// </summary>
/// <param name="data">有序数组</param>
/// <param name="val">查找的值</param>
/// <returns>如果找到,则返回在数组中的下标,否则返回-1</returns>
static int Search(int[] data, int val)
{
//如果数组为空,则直接返回-1
if(data.Length<=0)
return -1;
//设置初始上下限为数组的上下限
int low = 0;
int high = data.Length - 1;
//循环二分查找,直至找到指定元素或者查找完毕
while (low <= high)
{
//这里进行二分
int middle = (low + high) / 2;
//找到指定元素
if (data[middle] == val)
return middle;
//对二分后较大的那一半序列进行查找
else if (data[middle] < val)
low = middle+1;
//对二分后较小的那一半序列进行查找
else
high = middle-1;
}
//二分结束仍没有找到指定元素
return -1;
}
}
}
广积粮,筑高墙,缓称王