[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;
}