c語言實現的通用二分查找算法

//
/*
	二分查找是基於排好序的算法。複雜度低,並且很高效,
	由於項目中大量使用的了二分查找,但是又不能每個業務實現一個
	因此有必要實現一個通用的二分查找
	其主要思想:通過對已經排好序的數組,進行數據指針的比較。
	
	@const void *key 需要查找的key值
	@const void *base, 所要查找數據的首地址
	@int nmemb,所要查找的成員數量
	@int size, 每個元素的大小
	@int *piEqual,是否能查找到的標誌查到爲1,否則爲0
*/


int bsearch_int (const void *key, const void *base, int nmemb, int size, int *piEqual)
{
	size_t l, u, idx;
	const void *p, *p2;
	int comparison, comparison2;


	*piEqual = 0;
	if (nmemb < 0) return -1;
	if (!nmemb) return 0;
	l = 0;
	u = nmemb;


	while (l < u)
	{
		idx = (l + u) / 2;
		p = (void *) (((const char *) base) + (idx * size));
		comparison = *(int *)key - *(int *)p ;


		if (comparison == 0)
		{
			*piEqual = 1;
			return idx;
		}		
		else if (comparison < 0)
		{
			if (idx == 0) return idx;


			p2 = (void *) (((const char *) base) + ((idx - 1) * size));
			comparison2 = *(int *)key - *(int *)p2 ;


			if (comparison2 > 0) return idx;


			u = idx;
		}
		else /*if (comparison > 0)*/ 
		{
			l = idx + 1;
		}		
	}


	return u;
}

更多文章,歡迎關注http://blog.csdn.net/wallwind

版權聲明:可以任意轉載,轉載時請務必標明原始出處和作者信息



發佈了270 篇原創文章 · 獲贊 96 · 訪問量 232萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章