Common binary search algorithm implemented in C Language

Source: Internet
Author: User

[Cpp]
//
/*
Binary Search is an algorithm based on sorted order. Low complexity and high efficiency,
Because the project uses a lot of binary searches, but each business cannot implement one
Therefore, it is necessary to implement a common binary search.
The main idea is to compare data pointers by sorting arrays.

@ Const void * key value to be searched
@ Const void * base, the first address of the data to be searched
@ Int nmemb, number of members to be searched
@ Int size, the size of each element
@ Int * piEqual: indicates whether the flag that can be found is 1. Otherwise, it is 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;
}

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.