The realization of binary search method in C language

The binary search method is also called binary search. As the name implies, it divides the data into two halves, then judges which half of the key you are looking for, and repeats the above steps to find the target key;
Note: (cough cough, knock on the blackboard) The binary search method only Suitable for operations on arrays and data in an existing sequence! ! !
Obviously, the binary search method is much more efficient than other search methods such as sequential search;
let's take a practical operation and understand the meaning of binary search.
For example: to find the position of key=7 in the array arr[]={8,7,9,6,4,1,2,5,3,10,11}; first, we must first put the array arr in The data members are sorted. arr[]={1,2,3,4,5,6,7,8,9,10,11};
First round of search
As shown in the figure: the small end of this group of data is marked as low, the big end is marked as high, and the middle The value is denoted as mid; in
binary search, compare the searched key with mid, for example, key=7, you can narrow the search range between mid and high;
Second round of search
as shown in the figure, you can find key=low=7;
note : (Knock the blackboard) If the middle number mid is not an integer, it needs to be rounded.

code show as below:

#include<stdio.h>
int BinSearch(int arr[],int len,int key)                          //折半查找法(二分法)
{
    
    
	int low=0;                         //定义初始最小
	int high=len-1;                 //定义初始最大
	int mid;                            //定义中间值
	while(low<=high)
	{
    
    
		mid=(low+high)/2;              //找中间值
		if(key==arr[mid])               //判断min与key是否相等
			return mid;    
		else if(key>arr[mid])             //如果key>mid  则新区间为[mid+1,high]
			low=mid+1;
		else                                       //如果key<mid  则新区间为[low,mid-1]
			high=mid-1;
	}
	return -1;                             //如果数组中无目标值key,则返回 -1 ;
}
int main()
{
    
    
	int arr[]={
    
    1,2,3,4,5,6,7,8,9,10,11};                      //首先要对数组arr进行排序
	printf("%d \n",BinSearch(arr,(sizeof(arr)/sizeof(arr[0])),7));
	return 0;
}

The results are as follows:

Insert picture description here
Hope to help you!

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/88934984
Recommended