Binary search/binary search ------ algorithm idea

Binary search/binary search (this method is only used for sequential arrangement)

The algorithm is an efficient way to find numbers

假设n个数  次数=log2n  如找232次个数,只需要32

Steps:
1. Set left= the base of the initial digit (0), right= the base of the last digit, mid=(left+right)/2
2. Constantly fold in half to compare with the number you want to find (k)
3. If a[mid]>k, then mid is obviously to the left of k, left=mid+1; if a[mid]<k, then mid is obviously to the right of k, right=mid-1;
repeat 1, 2, 3 steps, when a[mid]=k, find the number k, that is, output mid base

For example, a[10]={1,2,3,4,5,6,7,8,9,10} Find a number in the array, and output its base.
If you find the number 7, the output shows the base 6
left=0 ,right=9,mid=(left+right)/2=4, at this time a[mid]=5<7,left=mid+1=5
left=5,right=9,mid=(left+right) /2=7, at this time a[mid]=8>7,right=mid-1=7
left=5,right=7,mid=(left+right)/2=6, at this time a[mid]= 7=7,
if you use the normal search method to find the output mid
, it will take 7 times to find it from the first position, which greatly reduces the efficiency

#define _CRT_SECURE_NO_WARNINGS 1
int main(){
    
    
	int a[10] = {
    
     1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	printf("请输入你想要的数字:");
	int k;
	scanf("%d",&k);//输入你想要的数字
	int left = 0;
	int right = 9;
	while (left <= right){
    
    //比较左右大小来得到想要数字的底数
		int mid = (left + right) / 2;
		if (a[mid] < k){
    
    
			left = mid + 1;
		}
		else if (a[mid]>k){
    
    
			right = mid - 1;
		}
		else{
    
    
			printf("它的底数是:%d\n", mid);
			break;
		}
	}
	if (left > right){
    
    
		printf("找不到奥!\n");
	}

	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43885306/article/details/112982021