C language: simple binary search

topic

Use binary search to find a specified number in an array.

enter

The input consists of 3 lines, the first line contains an integer n, the second line contains n integers separated by spaces, and the third line contains an integer m.

output

If the integer m can be found in the sequence, the number is output (if there are multiple numbers, the smallest number is returned), if it does not exist, None is output.
Insert image description here

knowledge supplement

Binary search:
Binary search is also called binary search (Binary Search), which is a more efficient search method. However, binary search requires that the linear table must adopt a sequential storage structure, and the elements in the table must be arranged in order by keywords .

Understanding of ideas

Suppose you enter 10 numbers arranged from small to large, as follows
1 2 3 4 5 6 7 9 10 11
Suppose you want The search number key is 3, then the search process is as follows
1. The beginning is as follows
Insert image description here
2. At this time arr[mid] = 5, the key is less than 5, then Move high to the left of mid, that is, the position of mid-1
Insert image description here
3. Recalculate the value of mid to 2, as follows
Insert image description here
4. At this time key= 2=arr[mid], then exit the loop and find the key 2


The code is implemented as follows
#include<stdio.h>
int main(void)
{
    
    
	int n, m, arr[40];
	int mid, low, high, key;
	scanf_s("%d", &n);
	for (int i = 1; i <= n; i++)
	{
    
    
		scanf_s("%d", &arr[i]);
	}
	scanf_s("%d", &m);

	//如果能够在序列中找到整数m,则输出编号(如果存在多个编号,返回编号最小的),如果不存在,则输出None。
	low = 1;
	high = n; 
	key = m; //m为要查找的数
	//循环进行的条件low<=high
	while (low <= high)
	{
    
    
		mid = (low + high) / 2;
		//如果要找的数key比arr[mid]小,将high重新定义为下标mid前一个下标值
		if (key < arr[mid])
		{
    
    
			high = mid - 1;
		}
		//如果要找的数key比arr[mid]大,将low重新定义为下标mid后一个下标值
		else if (key > arr[mid])
		{
    
    
			low = mid + 1;
		}
		//如果要找的数key与arr[mid]相等,则退出循环
		else if(key == arr[mid])
		{
    
    
			printf("%d\n", mid);
			goto END;
		}
		printf("None");
	}
	END:;
	return 0;
}(✪ω✪)

If you have any questions, point them out, discuss them together, and make progress together (✪ω✪).

Guess you like

Origin blog.csdn.net/lalala_dxf/article/details/120106732#comments_28718056