Searches a section of the sorted ArrayList for an element, using a binary search algorithm, and returns the index of the element.
[Visual Basic] Overridable Public Function BinarySearch( _ ByVal index As Integer, _ ByVal count As Integer, _ ByVal value As Object, _ ByVal comparer As IComparer _ ) As Integer [C#] public virtual int BinarySearch( int index, int count, object value, IComparer comparer ); [C++] public: virtual int BinarySearch( int index, int count, Object* value, IComparer* comparer ); [JScript] public function BinarySearch( index : int, count : int, value : Object, comparer : IComparer ) : int;
-or-
a null reference (in Visual Basic Nothing) to use the IComparable implementation of each element.
The index of the value in the sorted ArrayList, if value is found. Otherwise, a negative number, which is the bitwise complement of the index of the next element.
Exception Type | Condition |
---|---|
ArgumentException | index and count do not denote a valid range in the ArrayList.
-or- comparer is a null reference (Nothing), and neither value nor the elements of ArrayList implement the IComparable interface. -or- comparer is a null reference (Nothing), and value is not of the same type as the elements of the ArrayList. |
ArgumentOutOfRangeException | index is less than zero.
-or- count is less than zero. |
This method can be overridden by a derived class.
If comparer is provided, the elements of the ArrayList are compared to the specified value using the specified IComparer interface.
If comparer is a null reference (Nothing), the comparison is done using the IComparable implementation provided by the element itself or by the specified value.
a null reference (Nothing) can always be compared with any other type; therefore, comparisons with a null reference (Nothing) will not generate an exception when using IComparable. When sorting, a null reference (Nothing) is considered to be less than any other object.
The specified range of the ArrayList must already be sorted using the specified BinarySearch method; otherwise, the result will be incorrect.
If the ArrayList does not contain the specified value, the method returns a negative integer. The bitwise complement operator (~) can be applied on this negative integer to retrieve the index of the first element that is larger than the search value. If inserting the value into the ArrayList, this index should be used as the insertion point to maintain the sort order.
This method is an O(log
ArrayList Class | ArrayList Members | System.Collections Namespace