1. 程式人生 > >寫一個函式,實現一個整形有序陣列的二分查詢

寫一個函式,實現一個整形有序陣列的二分查詢

程式程式碼:

#include <stdio.h>
#include <windows.h>
int binary_search(int arr[], int num, int left, int right)
{
	int mid = 0;
	while (left <= right)
	{
		mid = left - (left - right) / 2;
		if (arr[mid]>num)
		{
			right = mid - 1;
		}
		else if (arr[mid] < num)
		{
			left = mid + 1;
		}
		else
		{
			return mid;
		}
	}
	if (left>right)
	{
		return -1;
	}
}
int main()
{
	int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int a = binary_search(arr,7, 5, 8);
	if (a != -1)
	{
		printf("找到了,下標%d\n", a);
	}
	else
	{
		printf("沒找到\n");
	}
	system("pause");
	return 0;
}

程式執行結果: