Analysis of the binary search algorithm in C language

Define:

In a sense, it is to execute once to get the remaining subscripts (beginning and end)/2 to an intermediate quantity, and then compare to find the number you want to find. Such an algorithm will make the execution process N times simpler.  

Written in the front: I am just a little white who constantly exercises myself on the blog, hoping to be liked by everyone, if there is any problem, we can communicate and make progress together.

Next we give a simple example to show my thoughts. Hope readers can understand the meaning of the code! ! ! ! ! ! !

#include <stdio.h> 
#include <string.h> 
#include <Windows.h> 
#include <stdlib.h> 
int main() 
{ 
	int a,sz,left,right,mid; 
	int num[]={ 1,2,3,4,5,6,7,8,9,10}; 
	printf ("Please enter a number:\n"); 
	scanf ("%d",&a); 
	sz=sizeof(num) /sizeof(num[0])-1; //Calculate the number of arrays 
	left=0; //Define the start and end subscript values ​​of the array 
	right=sz-1; 
	while (left<=right) //Loop body loop, need Readers can comprehend 
	{ 
		mid=(left+right)/2; 
	if(num[mid]>a) 
	{ 
		right=mid-1; 
	}
	
	else if(num[mid]<a)
	{
			left=mid+1; 
	} 
	else 
	{ 
		printf ("Found it, the subscript is:%d",mid); 
		break; 
	} 
	} 
	if(left>right) 
	{ 
		printf ("Sorry not found\n"); 
	} 

		

	
	return 0; 
}


Guess you like

Origin blog.51cto.com/15144773/2674893