【C语言】折半查找

#include 

int Search(int arr[], int n, int m)
{
	int left = 0;
	int right =m;
	while (left <= right)
	{
		int mid = left + (right - left) / 2;
		if (arr[mid] == n)
		{
			return n;
		}
		else if (arr[mid] < n)
		{
			left = mid + 1;
		}
		else  if (arr[mid] > n)
		{
			right = mid - 1;
		}
	}

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

	if (ret != -1)
	{
		printf("找到了,是 %d", key);
		printf("\n");
	}
	else
		printf("没找到\n");
	return 0;
}

你可能感兴趣的:(c语言)