C语言-递归二分法查找

只愿长相守 提交于 2020-02-19 06:08:32
#include <stdio.h>
int search(int *var, int target, int low, int high)
{
	int mid = (low + high)/2;
	while (low < high)
	{
		
		if (target > var[mid])
		{
			return search(var, target, mid + 1, high);
		}
		else if (target < var[mid])
		{
			return search(var, target, low, mid - 1);
		}
		else 
		{
			printf("The firt matching position is: %d \n", mid);
			return mid;
		}
	}
	return -1;
}
int main()
{
	int array[20] = {2, 12, 78, 98, 245, 320, 417, 578, 643, 708, 923, 978, 996, 1002, 1200, 2300, 2398, 2400, 2521, 2888};
	int target = 23;
	int length = sizeof(array)/sizeof(int);
	if (search(array, target, 0, length) == -1)
	{
		printf("Can not find the target. \n");
	}
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!