Note:
This is something I usually write.Code, May not be useful and in line with the design principles. If anything is inappropriate, please advise.
Note:
ThisAlgorithmSimilar to another general fast sorting algorithm, the logic of the algorithm is fixed. However, due to the differences between the data source and the comparison or search logic, the process of data processing is coupled with the algorithm logic, so we have to implement different data sources and comparison logics. Therefore, to abstract the algorithm logic, you must extract the data operation and comparison interfaces.
For the binary search algorithm, the data source can be indexed. The algorithm tries to compare the data at different indexes to determine the direction of the target data. On the other hand, the algorithm user must be familiar with the data source and know the index to determine the specific data.
Therefore, this algorithm ignores the specific data source and requires the caller to inform the index range of the data source, and provides the logic for comparing the data at the specified index (as a delegate ).
In this way, algorithms only need to operate on indexes and are isolated from specific data sources. The comparison logic and can be customized by users.
Example:
Code Searchalgorithm. bisearchmatch match = Delegate ( Int Index)
{
Return Branchid. compareto (allbranchlist [Index]. ID );
};
Elementidx = Searchalgorithm. bisearch ( 0 , Allbranchlist. Count - 1 , Match );
Source code:
Code /// <Summary>
/// Half-lookup match parameter prototype
/// </Summary>
/// <Param name = "Index"> Index generated by bisearch </Param>
/// <Returns> 0: the data at the index is matched successfully. 1: The data to be searched is between the index and the upper limit.-1: The data to be searched is between the index and the lower limit. </Returns>
Public Delegate Int Bisearchmatch ( Int Index );
/// <Summary>
/// Semi-query: This function generates possible indexes based on the upper and lower bounds and calls the match delegate one by one using the generated indexes until the matching is successful or there are no other possible indexes.
/// </Summary>
/// <Param name = "lbound"> Lower Bound </Param>
/// <Param name = "ubound"> Upper Bound </Param>
/// <Param name = "match"> Match delegate </Param>
/// <Returns> If the return value is within the range (lbound, ubound), the search is successful and the return value is the index to be searched. If the return value is smaller than the lower limit, the search index is not found. </Returns>
Public Static Int Bisearch ( Int Lbound, Int Ubound, bisearchmatch match)
{
Int Mid, result, templbound = Lbound;
If(Lbound>Ubound|Match= Null)ReturnLbound- 1;
While (Lbound <= Ubound)
{
Mid = Lbound + (Ubound - Lbound) > 1 );
Result = Match (MID );
If (Result = 0 )
Return Mid;
Else If (Result > 0 )
Lbound = Mid + 1 ;
Else
Ubound = Mid - 1 ;
}
ReturnTemplbound- 1;
}