A universal binary lookup algorithm based on C language

Source: Internet
Author: User
Tags int size
/* Binary lookup is an algorithm based on good order.
	
	The complexity is low, and very efficient, because the project in a large number of use of two-point lookup, but not each business implementation of one so it is necessary to implement a common binary search its main idea: through the ordered array, the data pointer comparison. @const void *key need to find the key value @const void *base, the first address to find the data @int Nmemb, the number of members to find @int size, the size of each element @int *piequal, whether it can be found The flag is found to be 1, otherwise 0 */int bsearch_int (const void *key, const void *base, int nmemb, int size, int *piequal) {size_t L, u, id
	X
	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; }

More articles, welcome attention Http://blog.csdn.net/wallwind

Copyright NOTICE: You can reprint, reprint, please be sure to indicate the original source and author information

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.