C# | List<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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the 
// List<T>.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);
        }
    }
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the 
// List<T>.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);
    }
}

chevron_right


Output:

Original List
5
6
1
9

List in Sorted form
1
5
6
9

Insert 3 :
1
3
5
6
9

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

2nd 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.