二分查找(递归与非递归)

1.非递归

#include
#include
int main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9,10 };
	int sz = sizeof(a) / sizeof(a[0]);
	int k = 7, l = 0, r = sz - 1, m;
	while (l <= r)
	{
		m = (l + r) / 2;
		if (a[m] < k)
			l = m + 1;
		else if (a[m] > k)
			r = m - 1;
		else 
		{
			printf("找到了,该元素下标是:%d\n", m);
			break;
		}
	}
	if(l > r) 
		printf("对不起,没有找到该元素\n");
    return 0;
}

2.递归

#include
#include
int find(int a[], int l, int r, int k)
{
	while (l <= r)
	{
		int mid = (l + r) / 2;
		if (a[mid] < k)
			return	find(a, mid + 1, r, k);
		else if (a[mid] > k)
			return find(a, l, mid - 1, k);
		else
			return mid;
	}
	return -1;
}
int main()
{
	int i, a[100], n, k;
	scanf("%d %d", &n, &k);
	for (i = 0; i < n; i++)
		scanf("%d", &a[i]);
	printf("找到了,下标为%d", find(a, 0, n-1, k));
}

你可能感兴趣的:(C语言经典题目,c语言,算法)