Binary search (binary search algorithm)
Binary search is also called binary search. The
core idea: control the search range, each time you find or exclude half of the last search data.
Steps:
1. First find the middle value mid of the interval
2. Compare the middle value mid with the value x If the required number x is smaller than mid, take the interval to the left of mid to continue binary search; if the required number x is greater than mid, take the interval to the right of mid to continue binary search; if the required value x=mid returns mid ;
Example
Use binary search to find a random value in an array of 0-9 and output
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
srand((unsigned int)time(0));
int x = rand() % 10;
printf("x:%d\n",x);
int left = 0;
int right = 9;
while (left <= right)
{
int mid = (left + right) / 2; //取mid左右区间的中点
if (x < mid) //如果要求的数比mid小就取mid左边的区间
{
right = mid - 1; //因为上面已经比较过x和mid;所以不用再比较mid取mid-1为右端点
}
else if (x > mid) //如果要求的数比mid大就取mid右边的区间
{
left = mid + 1; //因为上面已经比较过x和mid;所以不用再比较mid取mid+1为左端点
}
else
{
printf("找到了:%d\n",mid);
return mid; //如果mid=x直接返回mid
}
}
printf("没找到\n");
return 0;
}
Note : The data for binary search needs to be sorted first