1. 程式人生 > >二分查詢(在整型有序陣列中查詢想要的數字,找到了返回下標,找不到返回

二分查詢(在整型有序陣列中查詢想要的數字,找到了返回下標,找不到返回

在整型有序陣列中查詢想要的數字,找到了返回下標,找不到返回 - 1
#include<stdio.h>
#include<Windows.h>
int binary_search(int arr[], int key, int sz)
{
	int left = 0;
    int right = sz - 1;
	while (left <= right)
	{
		int mid = left+(right-left)/2;
		if(arr[mid] == key)
		{
			return mid;
		}
		else if(arr[mid] > key)
		{
			right = mid-1;
		}
		else 
		{
			left = mid+1;
		}
	}
	return -1;
}
int main()
{
	int arr[10] = {1,2,3,4,5,6,7,8,9,10};
	int key = 6;
	int sz = sizeof( arr)/ sizeof(arr[0]);
	int ret = binary_search(arr, key, sz);
	if (ret == -1)
	{
		printf("找不到");
	}
	else
	{
		printf("找到了");
	}
	printf("\n");
	system("pause");
	return 0;
}