Linux C一站式学习习题答案11.6.1binarysearch

1、本节的折半查找算法有一个特点:如果待查找的元素在数组中有多个则返回其中任意一个,以本节定义的数组int a[8] = { 1, 2, 2, 2, 5, 6, 8, 9 };为例,如果调用binarysearch(2)则返回3,即a[3],而有些场合下要求这样的查找返回a[1],也就是说,如果待查找的元素在数组中有多个则返回第一个。请修改折半查找算法实现这一特性。

注:转载请注明源地址:http://blog.csdn.net/whorus1/article/list/2,谢谢!

#include<stdio.h>
#define LEN 10
#define k 4

int a[LEN] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5};

int find(int i, int j)
{
	int mid = i + (j - i)/2;
	if (a[mid] >= k) {
		if (a[i] == k)
			return i;
		find (i, mid - 1);
	} else  {
		find (mid + 1, LEN - 1);
	}
}

int main()
{
	printf ("%d\n",find (0, LEN - 1));
}


你可能感兴趣的:(Linux C一站式学习习题答案11.6.1binarysearch)