二分查找法
1. 二分查找的数组是有序的
2. 二分查找能够有效的减少有序数组的查询次数
3. 题目
利用二分查找法,查找某个数,如果存在则输出这个数,如果不存在,输出比它大的最小的数,输出比它小的最大的数,如果该数不在这个数组的范围内,就会报错 |
#include<stdio.h>
#include<stdlib.h>
void init(int array[],int num);
int binaryFind(int array[],int num,int findNum);
//06
void main()
{
int ret = 1;
int a[10] ={0};
init(a,sizeof(a)/sizeof(*a));
int findNum = 0;
printf("输入你想要查找的数:");
scanf("%d",&findNum);
ret = binaryFind(a,sizeof(a)/sizeof(*a),findNum);
if (ret == -1)
{
printf(" error: %d can't find the number %d",ret,findNum);
}
else
{
printf("the label is %d",ret+1);
}
system("pause");
}
//数组输入和排序
void init(int array[],int num)
{
int temp = 0;
//数组的录入
for (int i = 0;i< num;i++)
{
printf("请输入%d个数",i+1);
scanf("%d",&array[i]);
}
//冒泡排序
for(int i = 0;i< num;i++)
{
for(int j = 0;j<num-i-1;j++)
{
if(array[j]>array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
//二分查找
int binaryFind(int array[],int num,int findNum)
{
int ret = -2;
if (array == NULL)
{
return ret = -1;
}
//二分查找主要算法
int begin = 0;
int end = num -1;
int nowLable = 0;
if (findNum < array[0] || findNum > array[num -1])
{
return ret = -1;
}
while(begin <= end)
{
nowLable = (begin + end)/2;
if (array[nowLable]== findNum)
{
return nowLable;
}
if (array[nowLable]>findNum)
{
end = nowLable - 1;
}else
{
begin = nowLable + 1;
}
}
if (array[nowLable] > findNum)
{
printf("the biger number is %d\n",array[nowLable]);
printf("the lower number is %d\n",array[nowLable -1]);
}
else
{
printf("the biger number is %d\n",array[nowLable+1]);
printf("the lower number is %d\n",array[nowLable]);
}
return ret;
}