二分法查找

用了兩種方式來實現,一種是遞歸,一種是迭代,至於二分法的原理,到處都是,我這裏只是爲了練練手而已。

/*
 * return the index if success else return -1
 * recursion
 */
int dichotomySearch1(int *a, int m, int n, int key)
{
	int k = (m + n + 1)/2;
	if(m == n)
	{
		if(a[k] != key)
		{
			return -1;
		}
		else
		{
			return m;
		}
	}
	if(a[k] == key)
	{
		return k;
	}
	else if(a[k] < key)
	{
		return dichotomySearch1(a, k+1, n, key);
	}
	else if(a[k] > key)
	{
		return dichotomySearch1(a, m, k-1, key);
	}
}

int dichotomySearch2(int *a, int m, int n, int key)
{
	int k;
	do 
	{
		k = (m + n + 1)/2;
		if(a[k] == key)
		{
			return k;
		}
		else if(a[k] < key)
		{
			m = k + 1;
		}
		else if(a[k] > key)
		{
			n = k - 1;
		}
	} while (m != n);
	
	if(a[m] == key)
	{
		return m;
	}
	else
	{
		return -1;
	}
}

void TestDichotomySearch()
{
	int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17};
	int key = 2;
	int k = -1;

	k = dichotomySearch1(arr, 0, sizeof(arr)/sizeof(int) - 1, key);
	printf("dichotomySearch1: k is %d\n", k);

	k = dichotomySearch2(arr, 0, sizeof(arr)/sizeof(int) - 1, key);
	printf("dichotomySearch2: k is %d\n", k);
}

int _tmain(int argc, _TCHAR* argv[])
{
	TestDichotomySearch();

	return 0;
}

 

要用可以直接用,代碼已經簡單測試過。

点赞