Arrays and functions are essentially the same

They are all mapping
incoming parameters and returning results

Different:
Function: consumes computing resources
Array: consumes storage resources
In the algorithm, time is exchanged for space, and space is exchanged for time

C language implements binary search

#include <stdio.h>
int main()
{
    
    
	int k = 0;
	scanf("%d", &k);
	int arr[] = {
    
     0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int sz = sizeof(arr) / sizeof (arr[0]);
	int low = 0;
	int high = sz-1;
	while (low <= high)
	{
    
    
		int mid = (low + high) / 2;
		if (arr[mid] > k)
		{
    
    
			high = mid - 1;
		}
		else if (arr[mid] < k)
		{
    
    
			low = mid + 1;
		}
		else
		{
    
    
			printf("找到了,它是:%d", arr[a]);
			break;
		}
	}
	if (l>r)
		printf("没找到,请重新输入");
	return 0;
}

C++ implements binary search

#include <stdio.h>
int main()
{
    
    
	int k = 0;
	scanf("%d", &k);
	int arr[] = {
    
     0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int sz = sizeof(arr) / sizeof (arr[0]);
	int low = 0;
	int high = sz-1;
	while (low <= high)
	{
    
    
		int mid = (low + high) / 2;
		if (arr[mid] > k)
		{
    
    
			high = mid - 1;
		}
		else if (arr[mid] < k)
		{
    
    
			low = mid + 1;
		}
		else
		{
    
    
			printf("找到了,它是:%d", arr[a]);
			break;
		}
	}
	if (l>r)
		printf("没找到,请重新输入");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44659309/article/details/129980793