IListExtensionMethodsBinarySearchT Method |
Searches for the element specified in the sorted list specified using binary search http://en.wikipedia.org/wiki/Binary_search. The algorithm
is re-implemented here to be able to search in any sorted IList implementing data structure (.NET's BCL only implements BinarySearch on arrays and
List(Of T). If no IComparer(Of T) is available, try using Algorithmia's ComparisonBasedComparer,
Namespace:
SD.Tools.BCLExtensions.CollectionsRelated
Assembly:
SD.Tools.BCLExtensions (in SD.Tools.BCLExtensions.dll) Version: 1.1.1
Syntax public static int BinarySearch<T>(
this IList sortedList,
T element,
IComparer<T> comparer
)
<ExtensionAttribute>
Public Shared Function BinarySearch(Of T) (
sortedList As IList,
element As T,
comparer As IComparer(Of T)
) As Integer
Parameters
- sortedList
- Type: System.CollectionsIList
The sorted list. - element
- Type: T
The element. - comparer
- Type: System.Collections.GenericIComparerT
The comparer.
Type Parameters
- T
Return Value
Type:
Int32The index of the element searched or the bitwise complement of the index of the next element that is larger than
element or if there is no larger element the bitwise complement of Count. Bitwise complements have their original bits negated. Use
the '~' operator in C# to get the real value. Bitwise complements are used to avoid returning a value which is in the range of valid indices so
callers can't check whether the value returned is an index or if the element wasn't found. If the value returned is negative, the bitwise complement
can be used as index to insert the element in the sorted list to keep the list sorted
Usage Note
In Visual Basic and C#, you can call this method as an instance method on any object of type
IList. When you use instance method syntax to call this method, omit the first parameter. For more information, see
Extension Methods (Visual Basic) or
Extension Methods (C# Programming Guide).
Remarks Assumes that sortedList is sorted ascending. If you pass in a descending sorted list, be sure the comparer is adjusted as well.
See Also