As an extension of bsearch in stdlib, let's look at the statement:
Void * bsearch (const void * key, const void * base, size_t nelem, size_t width, int (* fcmp) (const void *, const *));
Parameters:
First: the keyword to be searched.
Second: the array to be searched.
Third: specify the number of elements in the array.
Fourth: the length of each element (in characters ).
Fifth: pointer to the comparison function.
In fact, sometimes it is not enough to judge by only two parameters in fcmp. If expansion can be increased and auxiliary variables can be passed in, it will be better.
The following is my implementation and test code:
[Cpp] view plaincopyprint?
# Include <iostream>
Using namespace std;
# Define INVALID_INDEX-10
Int IntCompare (const int & a, const int & B, void * param)
{
Return a-B;
}
Template <class T1, class T2>
Int BinarySearch (const T1 * theArray,
Int length,
Const T2 & key,
Int (* compare) (const T1 &, const T2 &, void * param ),
Void * param)
{
Int indexRet = INVALID_INDEX;
Int mid = length/2;
Int cmp = compare (theArray [mid], key, param );
If (cmp = 0)
{
IndexRet = mid;
}
Else if (length! = 1)
{
If (cmp <0 & length! = 1)
{
// The intermediate element is smaller than the key, indicating that the element is on the right.
IndexRet = BinarySearch (theArray + mid, length-mid, key, compare, param );
If (indexRet! = INVALID_INDEX)
{
IndexRet + = mid;
}
}
Else
{
IndexRet = BinarySearch (theArray, mid, key, compare, param );
}
}
Return indexRet;
}
Int main ()
{
Int length = 0;
Int I = 0;
Int key = 0;
Int index = INVALID_INDEX;
Cin> length;
Int * aArray = new int [length];
For (I = 0; I <length; I ++)
{
Cin> aArray [I];
}
Cin> key;
Index = BinarySearch (aArray, length, key, IntCompare, NULL );
If (index = INVALID_INDEX)
{
Cout <"The element is not exist." <endl;
}
Else
{
Cout <"The element position is" <index <"." <endl;
}
Delete aArray;
Return 0;
}
Input:
10
1 2 3 4 5 6 7 8 9 10
5
Output:
The element position is 4.
The first row is the number of array elements n, the second row is n Array elements, and the last is the key to be searched.
Code Description:
Template <class T1, class T2> // use the template
Int BinarySearch (const T1 * theArray, // array to be searched
Int length, // Number of array elements
Const T2 & key, // The key to be searched. The type does not need to be the same as the array.
Int (* compare) (const T1 &, const T2 &, void * param), // compare function pointer
Void * param) // additional comparison parameter, which will be passed into compare for auxiliary judgment
The following is basically a simple recursive binary search. It should be noted that when length = 1, it should be used as a recursive exit, and no recursion can be performed even if it cannot be found, otherwise, it will be an endless loop.
Because mid = length/2 = 1/2 = 0; the recursion behind it will cause problems.