查找一个有序数组中的一个元素——二分法

时间:2022-10-23 19:13:20
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int binary_search(int arr[], int sz,int key)
{
	int left = 0;
	int right = sz - 1;
	while (left <= right)
	{
		int mid = left + (right - left) / 2;   //求平均数(防止溢出
		if (arr[mid] < key)
		{
			left = mid + 1;
		}
		else if (arr[mid]>key)
		{
			right = mid - 1;
		}
		else
		{
			return mid;
		}
	}
}
int main()
{
	int mid = 0;
	int key = 14;
	int arr[] = { 0, 2, 3, 4, 5, 6, 7, 8, 10, 14 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int ret = binary_search(arr, sz, key);
	if (arr[ret] == key)
	{
		printf("找到了!下标是%d\n", ret);
	}
	else
	{
		printf("找不到\n");
	}
	system("pause");
	return 0;
}