写一个函数,实现一个整形有序数组的二分查找

#include<stdio.h>
#include<windows.h>
int binSearch(int arr[], int size, int x)
{
	int left = 0;
	int right = size - 1;
	int mid = 0;
	while (left <= right)
	{
		mid = left + ((right - left) / 2);
		if (x > arr[mid])
		{
			left = mid + 1;
		}
		else if (x < arr[mid])
		{
			right = mid - 1;
		}
		else
		{
			return mid;
		}
	}
	return -1;
}	
int main()
{
	int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int size = sizeof(arr) / sizeof(arr[0]);
	int x = 6;
	int index = binSearch(arr, size, x);
	if (index < 0)
	{
		printf("not found!\n");
		return 1;
	}
	printf("found it:%d\n", index);
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/zy_20181010/article/details/79951974