CircularListTBinarySearch(T, IComparerT) Method

Searches the entire sorted CircularListT for an element using the specified comparer and returns the zero-based index of the element.

Definition

Namespace: KGySoft.Collections
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 8.1.0
C#
public int BinarySearch(
	T item,
	IComparer<T> comparer
)

Parameters

item  T
The object to locate. The value can be for reference types.
comparer  IComparerT
The IComparerT implementation to use when comparing elements, or to use the Comparer for enum element types, or the default comparer Default for other element types.

Return Value

Int32
The zero-based index of item in the sorted list, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.

Remarks

The comparer customizes how the elements are compared. For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

If comparer is provided, the elements of the list are compared to the specified value using the specified IComparerT implementation.

If comparer is , then if T is an enum, this method uses the EnumComparer<TEnum>.Comparer; otherwise, the default comparer Comparer<T>.Default for type T to determine the order of list elements. The Comparer<T>.Default property checks whether type T implements the IComparableT generic interface and uses that implementation, if available. If not, Comparer<T>.Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.

The list must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

If comparer is , comparing with any reference type is allowed and does not generate an exception when using the IComparableT generic interface. When sorting, is considered to be less than any other object.

If the list contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

If the list does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operation (~) to this negative integer to get the index of the first element that is larger than the search value. When inserting the value into the CircularListT, this index should be used as the insertion point to maintain the sort order.

This method is an O(log n) operation, where n is the number of elements in the range.

Exceptions

InvalidOperationExceptioncomparer is , and the default comparer Default cannot find an implementation of the IComparableT generic interface or the IComparable interface for type T.

See Also