二分查找(binsearch)

//二分查找(binsearch)
//基于从小到大排列的有序数组实现
#include

typedef int Item;

//迭代
int binary_search(Item* nums, int nums_size, Item target)
{
	int low = 0, high = nums_size - 1;

	while (low <= high)
	{
		int mid = low + (high - low) / 2;          /*如果写成:mid = (high + low) / 2 有可能会溢出*/
		if (nums[mid] > target)
		{
			high = mid - 1;
		}
		else if (nums[mid] < target)
		{
			low = mid + 1;
		}
		else
		{
			return mid;                            /*找到了*/
		}
	}

	return -1;                                     /*找不到*/
}

//递归
int binary_search(Item* nums, int low, int high, Item target)
{
	int mid = low + (high - low) / 2;

	if (low <= high)
	{
		if (nums[mid] > target)
		{
			return binary_search(nums, low, mid - 1, target);
		}
		else if (nums[mid] < target)
		{
			return binary_search(nums, mid + 1, high, target);
		}
		else
		{
			return mid;                           /*找到了*/
		}
	}
	 
	return -1;                                    /*找不到*/
}

你可能感兴趣的:(算法(C语言描述),二分查找,算法,c语言)