This method searches for an element in the entire sorted List<T> using the default comparer and returns the zero-based index of the searched element.
public int BinarySearch (T item);
Here, item is the object which is to be locate and the value of item can be null or reference type.
Return Type: If the item is found, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element will be return and the complement is larger than that item. If there is no larger element, the bitwise complement of Count will be return.
Exception: This method will give InvalidOperationException if the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.
Below programs illustrate the use of above-discussed method:
The Original List is: ABCD QRST XYZ IJKL The List in Sorted form ABCD IJKL QRST XYZ Insert EFGH : ABCD EFGH IJKL QRST XYZ
Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T) method in the List by using a user define function.
Original List 5 6 1 9 List in Sorted form 1 5 6 9 Insert 3 : 1 3 5 6 9
- If the List<T> 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.
- The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.
- This method is an O(log n) operation, where n is the number of elements in the range.
- Method within method in java
- C# | Clone() Method
- C# | Math.Max() Method
- C# | Dictionary.Add() Method
- C# | Copy() Method
- C# | ToLower() Method
- C# | Math.Min() Method
- C# | ToUpper() Method
- C# | Math.Cos() Method
- C# | Math.Sin() Method
- C# | IndexOfAny() Method
- C# | Remove() Method
- C# | Math.Tan() Method
- C# | IsNullOrEmpty() Method
- Main Method in C#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.