Error-prone: function way to achieve binary search integer array

It is possible to implement a function to achieve binary search. The first thing we think of is the following code:

//二分查找
#include <stdio.h>
#include <string.h>
int cz_sz(int num[],int a)
{
	int left,right,mid;
	left=0;
	right=sizeof(num)/sizeof(num[0])-1;
	mid=(left+right)/2;
	while(left<=right)
	{

	if(num[mid]>a)
	{
		right=mid+1;
	}
	else
		if(num[mid]<a)
		{
			left=mid+1;
		}
		else
			return mid;
	}
	if(left>right)
		return 0;
}


int main()
{
	int left,right,mid;
	int a,t;
	int num[]={1,2,3,4,5,6,7,8,9,10};
	printf ("请输入你要查找的值:");
	scanf ("%d",&a); 
	t=cz_sz(num,a); 
	if(0==t) 
	{ 
		printf ("not found\n"); 
		
	} 
	else 
	{ 
		printf ("found, the subscript is: %d\n",t); 
	} 
	return 0; 

}

Then you will find embarrassingly:
when you input some numbers in the array, he actually returned one to me...not much to say the picture above:
M(}I109`J9JVFT0@J1RZD6T.png

???? What's going on

It turns out that the array is only passed the first address when passing the parameters. , So it will cause an error when calculating the length.
Our solution is to put the length of the calculated array in the main function and add an additional parameter to the main function to solve the problem.
Friends, we must remember: the formal parameter is actually just a temporary copy of the actual parameter. Changes to the formal parameter will not change the value of the actual parameter. The value can only be changed by establishing a connection through the call by address (in short: Use pointers!!!)

We can change the function as follows:

//二分查找
#include <stdio.h>
#include <string.h>
int cz_sz(int num[], int a, int b)
{
	int left, right, mid;
	left = 0;
	right = b - 1;
	
	while (left <= right)
	{
		mid = (left + right) / 2;

		if (num[mid] > a)
		{
			right = mid + 1;
		}
		else
			if (num[mid] < a)
			{
				left = mid + 1;
			}
			else
				return mid;
	}
	
		return 0;
}


int main()
{
	int a, t;
	int num[] = { 1,2,3,4,5,6,7,8,9,10 };
	int b = sizeof(num) / sizeof(num[0]);
	printf("Please enter the value you are looking for:"); 
	scanf_s("%d", &a);

	t = cz_sz(num,a,b); 
	if (0 == t) 
	{ 
		printf("not found\n"); 

	} 
	else 
	{ 
		printf("found , The subscript is: %d\n", t); 
	} 
	

}


Now there is no problem with the implementation. I hope readers can share the technology and point out any problems. Then, the scanf_s function is the specification requirement of my program in VS2019! ! ! ! !











Guess you like

Origin blog.51cto.com/15144773/2678897