二分查找

时间:2023-03-26 19:59:43
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

//int main()
//{
//	int a;
//	int b;
//	printf("请输入两个整数:\n");
//	scanf("%d%d", &a, &b);
//	float c = (float)a / b;
//	printf("两数之和为a+b=%d\n", a + b);
//	printf("两数之差为a-b=%d\n", a - b);
//	printf("两数之积为a*b=%d\n", a * b);
//	printf("两数之商为c=%f\n", c);
//	return 0;
//}

int Binary_search(int arr[],int ret, int sz)
{
	int left = 0;
	int right = sz;
	int z = sz / 2;

	while (left <= right)
	{
		z = (right + left) / 2;
		if (ret < arr[z])
		{
			right = z-1;
		}
		else if (ret > arr[z])
		{
			left = z+1;
		}
		else
		{
			return z;
	    }
	}
	return -1;
}

int main()
{
	int ret;
	int sz;
	int g;
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	sz = sizeof(arr) / sizeof(arr[0]);

	printf("请输入一个数字:  \n");
	scanf("%d", &ret);
	if (-1 == Binary_search(arr,ret,sz))
	{
		printf("没找到\n");
	}
	else
	{
		g = Binary_search(arr, ret, sz);
		printf("找到了,下标是:%d\n",g );
	}

	return 0;
}