Binary search (binary search)-the most common search method

Binary search

Example introduction
A: How much did you buy your shoes?
B: Guess
A: 1000?
B: No, it's higher.
A: 500?
B: Higher
A: 250?
B: It's low
...
Repeatedly, eliminating half of it at a time, you will definitely get the correct value in the end

Binary search

Advantages: fewer comparison times, fast search speed, and good average performance.

Disadvantages: The searched array must be a sorted array.

Time complexity: O(logN)

#include<stdio.h>
int binary_search(int key,int a[],int n)
{
    
    
	int high,mid,low,count;
	low=0;
	high=n-1;
	count=0;
	while(low<=high){
    
    
			mid=(high+low)/2;
		if(a[mid]==key){
    
    
			printf("查找成功,a[%d]=%d",mid,key);
			count=1;
			break; 
			
		}								
		else if(a[mid]<key)
		 	low=mid+1;
		else
			high=mid-1; 
	}
	if(count==0)
		printf("查找失败"); 
	return 0;
 } 
 int main(){
    
    
 	int i,n,a[100],key;
 	printf("请输入数组长度:\n");
 	scanf("%d",&n);
 	printf("请输入数组元素:\n");
 	for(i=0;i<n;i++)
 	scanf("%d",&a[i]);	
	printf("输入你要查找的元素:\n");
	scanf("%d",&key);
	binary_search(key,a,n);
	return 0;
 }


Guess you like

Origin blog.csdn.net/dd_Mr/article/details/104178934
Recommended