二分法c语言代码(递归、迭代)

递归代码如下:

include 

int BSearch(int d[], int target, int low, int high)
{//第二个参数是要找的数,返回下标
	if (low <= high)
	{
		int m = (low + high) / 2;
		if (target < d[m])
			return BSearch(d, target, low, m - 1);
		else if (target>d[m])
			return BSearch(d, target, m + 1, high);
		else
			return m;
	}
	return -1;
}



void main()
{
	int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 2000, 5000, 9999 };
	int c = BSearch(a, 2000, 0, 13);
	printf_s("c:%d\n", c);
	getchar();
}

迭代代码如下:

#include 

int BSearch(int d[], int target, int low, int high)
{//第二个参数是要找的数,返回下标
	int m;
	while (low <= high)
	{
		m = (low + high) / 2;
		if (target < d[m])
			high = m - 1;
		else if (target>d[m])
			low = m + 1;
		else
			return m;
	}
	return -1;
}



void main()
{
	int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 2000, 5000, 9999 };
	int c = BSearch(a, 2000, 0, 13);
	printf_s("c:%d\n", c);
	getchar();
}

代码思路很简单,在此不再说明!!

你可能感兴趣的:(C/C++,数据结构)