二分查找法:优点 :查找速度快 缺点: 插入删除数据较困难 并且要求数据是有序
//二分查找法
// array为数组首地址 num 为需要查找的数 from 为数组起始查找下标 to 为结尾下标
//返回值为数据在数组中的索引值 -1 表示没找到
int binarysort(int * array,int from,int to,int num)
{
while (from < to)
{
if (array[from] == num)
{
return from;
}
if (array[to] == num)
{
return to;
}
int mid = from + (to - from) / 2;
//若用mid = (from+to)/2 若(from+to)>整型的上限则会出现溢出问题
if (array[mid] == num)
{
return mid;
}
if (num > array[mid])
{
from = mid + 1;
mid = from + (to - from) / 2;
}
else
{
to = mid - 1;
mid = from + (to - from) / 2;
}
}
return -1;
}