二分查找(折半查找):
优点:比较次数少,查找快,稳定,占用系统内存较少
缺点:待查找的集合(数组)必须是有序,所以二分查找适用于不经常变动并且查找频率较多的序列中。
过程:找到集合的中间位置,来对比是否为所要查找的元素,如果是,查找结束,返回元素,如果不是,根据中间位置把集合分成前后两个子集合,再使用相同的方式,在子集合中进行查找,如果找到停止查找,一直到子集合为空,集合中没有要查找元素。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 二分查找
{
class Program
{
static void Main(string[] args)
{
int[] y = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
int rr = BinarySearch(y, 0, y.Length - 1, 8);
Console.Write(rr); //12
}
public static int BinarySearch(int[] arr, int low, int high, int key)
{
int mid = (low + high) / 2;
if (low > high)
return -1;
else
{
if (arr[mid] == key)
return arr[mid];
else if (arr[mid] > key)
return BinarySearch(arr, low, mid - 1, key);
else
return BinarySearch(arr, mid + 1, high, key);
}
}
}
}