# List BinarySearch() Method in C#

List<T>.BinarySearch() Method uses a binary search algorithm to locate a specific element in the sorted List<T> or a portion of it. There are 3 methods in the overload list of this method as follows:

• BinarySearch(T)
• BinarySearch(T, IComparer<T>)
• BinarySearch(Int32, Int32, T, IComparer<T>)
##### BinarySearch(T) Method

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.

Syntax:

`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:

Example 1:

 `// C# program to illustrate the  ` `// List.BinarySearch(T) Method ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG { ` `     `  `    ``// Main Method ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``// List creation ` `        ``List<``string``> Geek = ``new` `List<``string``>(); ` ` `  `        ``// List elements ` `        ``Geek.Add(``"ABCD"``); ` `        ``Geek.Add(``"QRST"``); ` `        ``Geek.Add(``"XYZ"``); ` `        ``Geek.Add(``"IJKL"``); ` ` `  ` `  `        ``Console.WriteLine(``"The Original List is:"``); ` `        ``foreach``(``string` `g ``in` `Geek) ` `        ``{ ` `             `  `            ``// prints original List ` `            ``Console.WriteLine(g); ` `             `  `        ``} ` ` `  `        ``Console.WriteLine(``"\nThe List in Sorted form"``); ` `         `  `        ``// sort the List ` `        ``Geek.Sort(); ` `     `  ` `  `        ``Console.WriteLine(); ` `        ``foreach``(``string` `g ``in` `Geek) ` `        ``{ ` `            ``// prints the sorted List ` `            ``Console.WriteLine(g); ` `             `  `        ``} ` ` `  `        ``Console.WriteLine(``"\nInsert EFGH :"``); ` `         `  `        ``// insert "EFGH" in the List ` `        ``//"EFGH" insert into its original  ` `        ``// position when the List is sorted ` `        ``int` `index = Geek.BinarySearch(``"EFGH"``); ` `         `  ` `  `        ``if` `(index < 0)  ` `        ``{ ` `             `  `            ``Geek.Insert(~index, ``"EFGH"``); ` `        ``} ` ` `  `        ``Console.WriteLine(); ` `         `  `        ``foreach``(``string` `g ``in` `Geek) ` `        ``{ ` `             `  `            ``// prints the sorted list ` `            ``// after inserting "EFGH" ` `            ``Console.WriteLine(g); ` `        ``} ` `    ``} ` `} `

Output:

```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.

 `// C# program to illustrate the  ` `// List.BinarySearch(T) Method ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG { ` `     `  `// method for inserting "3" ` `public` `void` `binarySearch(List<``int``> Geek) ` `{ ` `     `  `    ``// insert "3" in the List ` `    ``Console.WriteLine(``"\nInsert 3 :"``); ` ` `  `    ``// "3" insert into its original  ` `    ``// position when the List is  ` `    ``// sorted ` `    ``int` `index = Geek.BinarySearch(3); ` `     `  ` `  `    ``if` `(index < 0)  ` `    ``{ ` `        ``Geek.Insert(~index, 3); ` `    ``} ` ` `  `    ``foreach``(``int` `g ``in` `Geek) ` `    ``{ ` `         `  `        ``// prints the sorted list ` `        ``// after inserting "3" ` `        ``Console.WriteLine(g); ` `         `  `    ``} ` `} ` `} ` ` `  `// Driver Class ` `public` `class` `search { ` `     `  `    ``public` `static` `void` `Main() ` `    ``{ ` `         `  `        ``// List creation ` `        ``GFG gg = ``new` `GFG(); ` `         `  `        ``List<``int``> Geek = ``new` `List<``int``>() { ` `                              ``5, 6, 1, 9}; ` `                               `  `        ``Console.WriteLine(``"Original List"``); ` `     `  `        ``foreach``(``int` `g ``in` `Geek) ` `        ``{ ` `            ``Console.WriteLine(g); ` `            ``// prints original List ` `        ``} ` `     `  `        ``Console.WriteLine(``"\nList in Sorted form"``); ` `        ``Geek.Sort(); ` `     `  `        ``foreach``(``int` `g ``in` `Geek) ` `        ``{ ` `            ``Console.WriteLine(g); ` `            ``// prints the sorted List ` `        ``} ` `     `  `        ``// calling the method "binarySearch" ` `        ``gg.binarySearch(Geek); ` `    ``} ` `} `

Output:

```Original List
5
6
1
9

List in Sorted form
1
5
6
9

Insert 3 :
1
3
5
6
9
```
##### BinarySearch(T) Method

This method searches for an element in the entire sorted List using the specified comparer and returns the zero-based index of the searched element.

Syntax:

public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer);

Parameters:

• item : It is the item to locate and the value of the item can be null for reference types.
• comparer : It is the IComparer<T> implementation to use when comparing elements.

Return Value: If the item founds, 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 that is larger than item or, if there is no larger element, the bitwise complement of Count.

Exception: This method will give InvalidOperationException if the comparer is null, and 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 the above-discussed method:

Example 1:

 `// C# program to demonstrate the  ` `// List.BinarySearch(T,  ` `// IComparer) Method ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG : IComparer<``string``> { ` ` `  `    ``public` `int` `Compare(``string` `x, ``string` `y) ` `    ``{ ` `        ``if` `(x == ``null` `|| y == ``null``)  ` `        ``{ ` `            ``return` `0; ` `        ``} ` `        ``return` `x.CompareTo(y); ` `        ``//"CompareTo()" method ` `    ``} ` `} ` ` `  `// Driver Class ` `class` `geek { ` ` `  `    ``// Main Method ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``// list creation ` `        ``List<``string``> list1 = ``new` `List<``string``>(); ` ` `  `        ``// list elements ` `        ``list1.Add(``"B"``); ` `        ``list1.Add(``"C"``); ` `        ``list1.Add(``"E"``); ` `        ``list1.Add(``"A"``); ` ` `  `        ``// prints Original list ` `        ``Console.WriteLine(``"Original string"``); ` ` `  `        ``foreach``(``string` `g ``in` `list1) ` `        ``{ ` `            ``Console.WriteLine(g); ` `        ``} ` ` `  `        ``GFG gg = ``new` `GFG(); ` ` `  `         ``// sort the list ` `        ``list1.Sort(gg); ` `        `  `        ``// prits the sorted form of original list ` `        ``Console.WriteLine(``"\nList in sorted form"``); ` ` `  `        ``foreach``(``string` `g ``in` `list1) ` `        ``{ ` `            ``Console.WriteLine(g); ` `        ``} ` ` `  `        ``//"D" is going to insert ` `        ``//"gg" is the IComparer ` `        ``int` `index = list1.BinarySearch(``"D"``, gg); ` `        `  `        ``if` `(index < 0)  ` `        ``{ ` `            ``list1.Insert(~index, ``"D"``); ` `        ``} ` ` `  `        ``// prints the final List ` `        ``Console.WriteLine(``"\nAfetr inserting \"D\" in the List"``); ` `         `  `        ``foreach``(``string` `g ``in` `list1) ` `        ``{ ` `            ``Console.WriteLine(g); ` `        ``} ` `    ``} ` `} `

Output:

```Original string
B
C
E
A

List in sorted form
A
B
C
E

Afetr inserting "D" in the List
A
B
C
D
E
```

Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T, Comparer <T>) method in the List by using a user define function.

 `// C# program to demonstrate the  ` `// List.BinarySearch(T,  ` `// IComparer) Method ` `using` `System; ` `using` `System.Collections.Generic; ` `  `  `class` `GFG : IComparer<``int``> { ` ` `  `    ``public` `int` `Compare(``int` `x, ``int` `y) ` `    ``{ ` `        ``if` `(x == 0 || y == 0)  ` `        ``{ ` `            ``return` `0; ` `        ``} ` `        ``return` `x.CompareTo(y); ` `    ``} ` `} ` `  `  `// Driver Class ` `class` `geek { ` ` `  `    ``// Main Method ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``// list creation ` `        ``List<``int``> list1 = ``new` `List<``int``>() { ` `                               ``5, 6, 1, 9}; ` `  `  `        ``// prints Original list ` `        ``Console.WriteLine(``"Original string"``); ` ` `  `        ``foreach``(``int` `g ``in` `list1) ` `        ``{ ` `            ``Console.WriteLine(g); ` `        ``} ` `  `  `         ``// creating object of class GFG ` `        ``GFG gg = ``new` `GFG(); ` `      `  `        ``// sort the list ` `        ``list1.Sort(gg); ` `         `  `        ``// prits the sorted form  ` `        ``// of original list ` `        ``Console.WriteLine(``"\nList in sorted form"``); ` ` `  `        ``foreach``(``int` `g ``in` `list1) ` `        ``{ ` `            ``Console.WriteLine(g); ` `        ``} ` ` `  `        ``bSearch b = ``new` `bSearch(); ` `        ``b.binarySearch(list1); ` `    ``} ` `} ` `  `  `class` `bSearch { ` ` `  `    ``public` `void` `binarySearch(List<``int``> list1) ` `    ``{ ` ` `  `        ``// creating object of class GFG ` `        ``GFG gg = ``new` `GFG(); ` `  `  `        ``// "3" is going to insert ` `        ``// "gg" is the IComparer ` `        ``int` `index = list1.BinarySearch(3, gg); ` `         `  `        ``if` `(index < 0)  ` `        ``{ ` `            ``list1.Insert(~index, 3); ` `        ``} ` `  `  `        ``// prints the final List ` `        ``Console.WriteLine(``"\nAfter inserting \"3\" in the List"``); ` `        ``foreach``(``int` `g ``in` `list1) ` `        ``{ ` `            ``Console.WriteLine(g); ` `        ``} ` `    ``} ` `} `

Output:

```Original string
5
6
1
9

List in sorted form
1
5
6
9

After inserting "3" in the List
1
3
5
6
9
```
##### BinarySearch(Int32, Int32, T, IComparer<T>)

This method is used to search a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

Syntax:

public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);

Parameters:

index: It is the zero-based starting index of the range to search.

count: It is the length of the range to search.

item: It is the object to locate. The value can be null for the reference type.

comparer: It is the IComparer implementation to use when comparing elements, or null to use the default comparer Default.

Return Value: It returns the zero-based index of item in the sorted List<T>, if the 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.

Exceptions:

• ArgumentOutOfRangeException: If the index is less than 0 or count is less than 0.
• ArgumentException: If the index and count do not represent a valid range.
• InvalidOperationException: If the comparer is null.

Example:

 `// C# program to demonstrate the  ` `// List.BinarySearch(Int32,  ` `// Int32, T, Comparer ) method ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG : IComparer<``int``> ` `{ ` `public` `int` `Compare(``int` `x, ``int` `y) ` `{ ` `    ``if` `(x == 0 || y == 0) ` `    ``{ ` `        ``return` `0; ` `    ``} ` `    ``return` `x.CompareTo(y); ` `} ` `} ` ` `  `class` `search { ` `     `  `// "binarySearch" function ` `public` `void` `binarySearch(List<``int``> list1, ` `                                  ``int` `i) ` `{ ` `    ``Console.WriteLine(``"\nBinarySearch a "``+ ` `                   ``"range and Insert 3"``); ` `     `  `    ``// "gg" is the object of class GFG ` `    ``GFG gg = ``new` `GFG(); ` `     `  `    ``// binary search ` `    ``int` `index = list1.BinarySearch(0, i, ` `                                 ``3, gg); ` ` `  ` `  `    ``if` `(index < 0) ` `    ``{ ` `         `  `        ``// insert "3" ` `        ``list1.Insert(~index, 3); ` `        ``i++; ` `    ``} ` `     `  `    ``Display(list1); ` `} ` ` `  `// "Display" function  ` `public` `void` `Display(List<``int``> list)  ` `{ ` `     `  `    ``foreach``( ``int` `g ``in` `list ) ` `    ``{ ` `        ``Console.WriteLine(g); ` `    ``} ` `} ` `} ` ` `  `// Driver Class ` `class` `geek ` `{ ` `     `  `    ``// Main Method ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``List<``int``> list1 = ``new` `List<``int``>() ` `        ``{ ` `            ``// list elements ` `            ``15,4,2,9,5,7,6,8,10 ` `             `  `        ``}; ` `     `  `        ``int` `i = 7; ` `        ``Console.WriteLine(``"Original List"``); ` `         `  `        ``// "d" is the object of  ` `        ``// the class "search" ` `        ``search d = ``new` `search(); ` `         `  `        ``// prints Original list ` `        ``d.Display(list1); ` `     `  `        ``// "gg" is the object  ` `        ``// of class GFG  ` `        ``GFG gg = ``new` `GFG(); ` `         `  `        ``Console.WriteLine(``"\nSort a range with "``+ ` `                       ``"the alternate comparer"``); ` `         `  `        ``// sort is happens between ` `        ``// index 1 to 7             ` `        ``list1.Sort(1, i, gg); ` `         `  `        ``// prints sorted list ` `        ``d.Display(list1); ` `         `  `        ``// call "binarySearch" function ` `        ``d.binarySearch(list1,i); ` `         `  `    ``} ` `} `

Output:

```Original List
15
4
2
9
5
7
6
8
10

Sort a range with the alternate comparer
15
2
4
5
6
7
8
9
10

BinarySearch a range and Insert 3
15
2
3
4
5
6
7
8
9
10
```

Note:

• 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.

Reference:

My Personal Notes arrow_drop_up 3rd year student of Information Technology JADAVPUR UNIVERSITY

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.

Article Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5083989,"math_prob":0.7182644,"size":11734,"snap":"2019-43-2019-47","text_gpt3_token_len":3236,"char_repetition_ratio":0.16214834,"word_repetition_ratio":0.39115134,"special_character_ratio":0.28941536,"punctuation_ratio":0.15604101,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9900679,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-11-12T01:06:36Z\",\"WARC-Record-ID\":\"<urn:uuid:731f7838-4c33-4b79-a0e8-d4378d0e8dba>\",\"Content-Length\":\"173552\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4dead352-73ea-4a6c-af33-1a3dd9ed9cc8>\",\"WARC-Concurrent-To\":\"<urn:uuid:7e7ad5d1-1f6b-4a91-ab1c-187fde2861ba>\",\"WARC-IP-Address\":\"23.221.72.19\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/list-binarysearch-method-in-c-sharp/\",\"WARC-Payload-Digest\":\"sha1:ZNGYSFS4CRKGSHEHXO26DKRB4Y4CPHRW\",\"WARC-Block-Digest\":\"sha1:LHNCQP6PAAPTRAFQKZTZ2E3I7DE44T2H\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-47/CC-MAIN-2019-47_segments_1573496664469.42_warc_CC-MAIN-20191112001515-20191112025515-00315.warc.gz\"}"}