C language classic search algorithm binary search (detailed)

One, search algorithm

Search is to find a specific information element in a large amount of information. In computer applications, search is a common basic operation, such as searching the symbol table in a compiler.

Two, binary search algorithm

1. Algorithm idea
This search algorithm is also called binary search, binary search, suitable for searching the sorted data set, time complexity O (log2n), high efficiency.
Suppose there is an ascending data set, first find the middle element in the ascending set, divide the data set into two subsets, compare the middle element with the key, and return if it is equal to the key, if it is greater than the key key, search in the previous data set, otherwise search in the latter subset until it is found, if not found, return -1.

2. Binary search step
(1) First determine the middle position of the entire search interval mid=(low+high)/2;

(2) Compare the key value to be checked with the key value of the middle position; if they are equal, the search is successful;

(3) If it is greater than, continue the binary search in the second half area.
If it is less than, then continue the binary search in the first half area.

(4) If the search is successful, return the index of the array where the keyword is located, and return -1 if not found;

3. Binary search C language implementation

#include <stdio.h>
#define MaxSize 100
typedef struct
{
    
    
	int list[MaxSize];
	int length;
}Table;
int BinarySearch(Table S, int x);

void main()
{
    
    
	Table T={
    
    {
    
    11,22,33,44,55,66,77,88,99},9};
	int i, find, x;
	printf("有序表中的元素:\n");
	for(i=0; i<T.length; i++)
		printf("%4d", T.list[i]);
	printf("\n请输入要查找的元素:");
	scanf("%d",&x);
	find= BinarySearch(T, x);
	if(find)
		printf("元素%d是顺序表中的第%d个元素。\n", x, find);
	else
		printf("没有找到该元素!\n");
}

//在有序表中折半查找元素x,如果找到,则返回该元素在表中的位置,否则返回0 
int BinarySearch(Table S, int x)
{
    
    
	int low, high, mid;
	low=0, high=S.length-1;  //设置待查找元素范围的下界和上届 
	while(low<=high)
	{
    
    
		mid= (low+high)/2;
		if(S.list[mid]==x)  //如果找到元素,则返回该元素所在的位置 
			return mid+1;
		else if(S.list[mid]<x)  //如果mid所指示的元素小于x,则修改low指针
			low= mid+1;
		else if(S.list[mid]>x)  //如果mid所指示的元素大于x,则修改high指针 
			high= mid+1; 
	}
}

01

Reference: "The Function and Algorithm of Program Language C/C++"

Guess you like

Origin blog.csdn.net/Viewinfinitely/article/details/112372054