Open In App

How to use Array.BinarySearch() Method in C# | Set -2

Improve
Improve
Like Article
Like
Save
Share
Report

Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

There are total 8 methods in the overload list of this method as follows:

Here, the first 4 methods are already discussed in Set-1. Last 4 methods will be discussed in this set

BinarySearch<T>(T[], T) Method

This method searches for a specific element in a sorted one-dimensional array. It will search the entire array. The search uses an IComparable<T> generic interface which is implemented by each element of the array or by a specific object.

Syntax: public static int BinarySearch<T>(T[] arr, T val);
Here, “T” is the type of the elements of the array.

Parameters:
arr: It is the one-dimensional sorted array to search for.
val: It is the object to search for.

Return Value: It returns the index of the specified valin the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows:

  • If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
  • If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
  • If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.

Exceptions:

  • ArgumentNullException: If the arr is null.
  • InvalidOperationException: If the T does not implement the IComparable<T> generic interface.

Example 1:




// C# program to demonstrate the use of 
// BinarySearch<T>(T[], T) method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        string[] arr = {"ABC", "XYZ",
                "JKL", "DEF", "MNO"};
  
        Console.WriteLine("Original array");
        foreach(string g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nAfter Sort");
  
        // sort the array
        Array.Sort(arr);
          
        foreach(string g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nBinarySearch for 'GHI':");
  
         // call "BinarySearch<T>(T[], T)" method
        int index = Array.BinarySearch(arr, "GHI");
  
        sort(arr, index);
         
    }
  
    // BinarySearch<T> method
    private static void sort<T>(T[] array, int index)
    {
        if (index < 0) 
        {
  
            // If the index is negative, 
            // it represents the bitwise
            // complement of the next 
            // larger element in the array.
            index = ~index;
  
            Console.Write("Sorts between: ");
  
            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index - 1]);
  
            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else 
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}


Output:

Original array
ABC
XYZ
JKL
DEF
MNO

After Sort
ABC
DEF
JKL
MNO
XYZ

BinarySearch for 'GHI':
Sorts between: DEF and JKL.

Example 2:




// C# program to demonstrate the use 
// of BinarySearch<T>(T[], T) method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        int[] arr = {5, 7, 1, 3, 4, 2};
  
        Console.WriteLine("Original array");
  
        foreach(int g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nAfter Sort");
    
        // sort the array
        Array.Sort(arr);
         
        foreach(int g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nBinarySearch for '6':");
  
        // call "BinarySearch<T>(T[], T)" method
        int index = Array.BinarySearch(arr, 6);
  
        sort(arr, index);
          
    }
  
    // BinarySearch<T> method
    private static void sort<T>(T[] array, int index)
    {
        if (index < 0) 
        {
  
            // If the index is negative,
            // it represents the bitwise
            // complement of the next 
            // larger element in the array.
            index = ~index;
  
            Console.Write("Sorts between: ");
  
            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index - 1]);
  
            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else 
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}


Output:

Original array
5
7
1
3
4
2

After Sort
1
2
3
4
5
7

BinarySearch for '6':
Sorts between: 5 and 7.

BinarySearch<T>(T[], T, IComparer<T>) Method

This method searches for a specific value in a one-dimensional sorted array specified using IComparer<T> generic interface.

Syntax: public static int BinarySearch<T> (T[] arr, T val, IComparer comparer);
Here, “T” is the type of the elements of the array.

Parameters:

arr: It is the one-dimensional sorted array to search for.
val: It is the object to search for.
comparer: It is theIComparer<T> implementation to use when comparing elements.

Return Value: It returns the index of the specified valin the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows:

  • If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
  • If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
  • If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.

Exceptions:

  • ArgumentNullException: If the array is null.
  • InvalidOperationException: If the comparer is null and T does not implement the IComparable<T> generic interface.
  • ArgumentException: If the comparer is null, and value is of a type that is not compatible with the elements of array.

Example:




// C# program to demonstrate the use of
// BinarySearch<T>(T[], T, IComparer<T>)
// method
using System;
using System.Collections.Generic;
  
class comparer : IComparer<string> {
  
    public int Compare(string x, string y)
    {
        return x.CompareTo(y);
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        string[] arr = {"ABC", "XYZ",
                "JKL", "DEF", "MNO"};
  
        Console.WriteLine("Original Array");
        foreach(string g in arr)
        {
            Console.WriteLine(g);
        }
  
         // IComparer<T> object
        comparer gg = new comparer();
         
        Console.WriteLine("\nAfter Sort");
  
        // sort the array
        Array.Sort(arr, gg);
          
        foreach(string g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nBinarySearch for 'GHI':");
  
        // search for "GHI"
        int index = Array.BinarySearch(arr, "GHI", gg);
        sort(arr, index);
          
    }
  
    // BinarySearch<T> method
    private static void sort<T>(T[] array, int index)
    {
        if (index < 0) {
  
            // If the index is negative,
            // it represents the bitwise
            // complement of the next 
            // larger element in the array.
            index = ~index;
  
            Console.Write("Sorts between: ");
  
            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index - 1]);
  
            if (index == array.Length)
                Console.WriteLine("end of array");
            else
                Console.WriteLine("{0}", array[index]);
        }
        else 
        {
            Console.WriteLine("Found at index {0}", index);
        }
    }
}


Output:

Original Array
ABC
XYZ
JKL
DEF
MNO

After Sort
ABC
DEF
JKL
MNO
XYZ

BinarySearch for 'GHI':
Sorts between: DEF and JKL

BinarySearch<T>(T[], Int32, Int32, T)

This method searches a range of elements in a one-dimensional sorted array for a value, using the IComparable<T> generic interface implemented by each element of the Array or a specified value.

Syntax: public static int BinarySearch<T> (T[] arr, int start, int len, T val);
Here, “T” is the type of the elements of the array.

Parameters:
arr: It is the one-dimensional sorted array to search for.
start: It is the starting index of the range to search.
len: It is the length of the range to search.
val: It is the object to search for.

Return Value: It returns the index of the specified valin the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows:

  • If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
  • If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
  • If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.

Exceptions:

  • ArgumentNullException: If array is null.
  • InvalidOperationException: If T does not implement the IComparable<T> generic interface.
  • ArgumentException: If start and len do not specify a valid range in array or value is of a type that is not compatible with the elements of array.
  • ArgumentOutOfRangeException: If start is less than the lower bound of array.

Example:




// C# program to demonstrate the use of 
// BinarySearch<T>(T[], Int32, Int32,
// T) method
using System;
using System.Collections.Generic;
  
class GFG {
  
    public static void Main()
    {
        int[] arr = { 1, 5, 3, 4, 2, 7 };
  
        Console.WriteLine("Original Array");
        foreach(int g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nAfter Sort");
  
        // sort the array
        Array.Sort(arr);
  
        foreach(int g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nBinarySearch for '6':");
  
        // search for "6" in a 
        // range of index 0 to 4
        int index = Array.BinarySearch(arr, 0, 4, 6);
          
        sort(arr, index);
    }
  
    // BinarySearch<T> method
    private static void sort<T>(T[] array, int index)
    {
        if (index < 0) {
  
            // If the index is negative,
            // it represents the bitwise
            // complement of the next 
            // larger element in the array.
            index = ~index;
  
            Console.Write("Sorts between: ");
  
            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index - 1]);
  
            if (index == array.Length)
                Console.WriteLine("end of array");
            else
                Console.WriteLine("{0}", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}", index);
        }
    }
}


Output:

Original Array
1
5
3
4
2
7

After Sort
1
2
3
4
5
7

BinarySearch for '6':
Sorts between: 4 and 5

BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) Method

This method searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer<T> generic interface.

Syntax: public static int BinarySearch<T> (T[] array, int start, int len, T val, IComparer<T> comparer);
Here, “T” is the type of the elements of the array.

Parameters:

arr: It is the one-dimensional sorted array to search for.
start: It is the starting index of the range to search.
len: It is the length of the range to search.
value: It is the object to search for.
comparer: It is the IComparer<T> implementation to use when comparing elements.

Return Value: It returns the index of the specified valin the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows:

  • If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
  • If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
  • If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.

Exceptions:

  • ArgumentNullException: If array is null.
  • InvalidOperationException: If T does not implement the IComparable<T> generic interface.
  • ArgumentException: If start and len do not specify a valid range in array or comparer is null and val is of a type that is not compatible with the elements of array.
  • ArgumentOutOfRangeException: If start is less than the lower bound of array or len is less than zero.

Example:




// C# program to demonstrate the use of
// BinarySearch<T>(T[], Int32, Int32,
// T, IComparer<T>) method
using System;
using System.Collections.Generic;
  
class comparer : IComparer<string> {
  
    public int Compare(string x, string y)
    {
  
        return x.CompareTo(y);
    }
}
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        string[] arr = {"ABC", "UVW", "JKL",
                       "DEF", "MNO", "XYZ"};
  
        Console.WriteLine("Original Array");
        foreach(string g in arr)
        {
            Console.WriteLine(g);
        }
  
        // IComparer<T> object
        comparer gg = new comparer();
          
        Console.WriteLine("\nAfter Sort");
   
        // sort the array
        Array.Sort(arr, gg);
          
        foreach(string g in arr)
        {
            Console.WriteLine(g);
        }
  
        Console.WriteLine("\nBinarySearch for 'GHI':");
  
         // search for "GHI"
         // search happens in the
        // range of index 1 to 4
        int index = Array.BinarySearch(arr, 1, 4, "GHI", gg);
         
        sort(arr, index);
    
    }
  
    // BinarySearch<T> method
    private static void sort<T>(T[] array, int index)
    {
        if (index < 0) {
  
            // If the index is negative,
            // it represents the bitwise
            // complement of the next 
            // larger element in the array.
            index = ~index;
  
            Console.Write("Sorts between: ");
  
            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index - 1]);
  
            if (index == array.Length)
                Console.WriteLine("end of array");
            else
                Console.WriteLine("{0}", array[index]);
        }
        else 
        {
            Console.WriteLine("Found at index {0}", index);
        }
    }
}


Output:

Original Array
ABC
UVW
JKL
DEF
MNO
XYZ

After Sort
ABC
DEF
JKL
MNO
UVW
XYZ

BinarySearch for 'GHI':
Sorts between: DEF and JKL

Reference:



Last Updated : 14 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads