二分查找,原理就是拿要查找的数number和数组最中间的数进行比较,如果如果查找的数number大于数组中间的数,就在右半边查找,如果小于就在左半边查找,直到找到要找的数。
实现方法:
1、定义变量,min用来存储最小的下标,max用来存储最大的下标,searchNumber=(min+max)/2,用来存储要比较的数的下标。
2、用要查找的数number和array[searchNumber]比较,如果number>array[searchNumber],在右半边查找,min=searchNumber;如果number<array[searchNumber],在左半边查找,max=searchNumber。
3、重复以上步骤
注意:1、如果查找的数在数组中不存在。
2、二分查找的前提是已经排序的数组。
第一种方法:
int[] arrayint = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int searchNumber = arrayint[8];
int subMin = 0;
int subMax = arrayint.Length - 1;
while (true)
{
int subSearch = (subMin + subMax) / 2;
if (searchNumber == arrayint[subSearch])
{
System.Console.WriteLine("要查找的数字为:" + searchNumber + "在数组的第" + subSearch + "个");
//judge = false;
break;
}
else if (searchNumber < arrayint[subSearch])
{
//如果查找到最左边,说明数字在数组中不存在,这个地方换成“||”,就会变成死循环,因为subMin=0,subMax=0的时候subSearch还没有取(subMin + subMax) / 2。
if (subMin == subSearch && subMax == subSearch)
{
System.Console.WriteLine("-1");
//judge = false;
break;
}
else subMax = subSearch;
}
else
{
//当循环到最右边,subMin为倒数第二个数8,subMax为最后一个数9,subSearch就会永远是8(subMin),死循环,
//这时候有两种情况,1、arrayint[subMax==searchNumber]即最后一个数是要找的数
//2、查找的数字超范围
if (subMin == subSearch)
{
if (arrayint[subMax] == searchNumber)
{
System.Console.WriteLine("要查找的数字为:" + searchNumber + "在数组的第" + subMax + "个");
//judge = false;
break;
}
else System.Console.WriteLine("-1");
}
else subMin = subSearch;
}
}
第二种方法:
//用递归函数实现二分查找
public int BinarySearchNumber(int[] array, int low, int higth, int number)
{
int key = (low + higth) / 2;
if (array[key] == number)
{
return key;
}
else if (array[key] < number)
{
if (low == key)
{
if (array[higth] == number)
return higth;
else return -1;
}
else return BinarySearchNumber(array, key, higth, number);
}
else
{
if (low == key && higth == key)
{
return -1;
}
else return BinarySearchNumber(array, low, key, number);
}
}
static void Main(string[] args)
{
Program a = new Program();
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int site = a.BinarySearchNumber(arr, 0, arr.Length - 1, 8);
System.Console.WriteLine("要查找的数字位置为:" + site);
System.Console.ReadLine();
}