Open In App

List BinarySearch() Method in C#

Improve
Improve
Like Article
Like
Save
Share
Report

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#




// 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);
        }
    }
}


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#




// 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);
    }
}


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#




// C# program to demonstrate the
// List<T>.BinarySearch(T,
// IComparer<T>) 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);
        
        // prints 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("\nAfter 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

After 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 defined function. 

C#




// C# program to demonstrate the
// List<T>.BinarySearch(T,
// IComparer<T>) 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);
         
        // prints 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#




// C# program to demonstrate the
// List<T>.BinarySearch(Int32,
// Int32, T, Comparer <T>) 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:  

 



Last Updated : 02 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads