Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
How to sort an Array in C# | Array.Sort() Method Set – 2
Next article icon

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

Last Updated : 14 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
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:

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

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:

  • https://docs.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=netframework-4.7.2


Next Article
How to sort an Array in C# | Array.Sort() Method Set – 2

S

SoumikMondal
Improve
Article Tags :
  • C#
  • Technical Scripter
  • CSharp-Arrays
  • CSharp-method

Similar Reads

  • How to sort an Array in C# | Array.Sort() Method Set – 2
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method
    9 min read
  • Array.BinarySearch(Array, Object) Method with examples in C#
    This method is used to search a specific element in the entire one-dimensional sorted array by using the IComparable interface which is implemented by each element of the array and by the specified object. Syntax: public static int BinarySearch (Array array, object value); Parameters: array: It is t
    4 min read
  • How to sort an Array in C# | Array.Sort() Method | Set – 4
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array) Method This method sorts the elements in an entire one-dimensional array using the IComparable implementation of ea
    5 min read
  • How to Sort an Array in C# | Array.Sort() Method Set - 1
    Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows: Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Metho
    8 min read
  • How to sort an Array in C# | Array.Sort() Method Set – 3
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, IComparer) Method Sort(Array, Array, IComparer) Method Sort(Array, Array) Method Sort(Array, IComparer) Method This
    6 min read
  • C# | Array.BinarySearch(Array, Object, IComparer) Method
    This method searches for a value in a one-dimensional sorted array using a specified IComparer interface. Syntax: public static int BinarySearch(Array arr, Object val, IComparer comparer) Parameters: arr : The one-dimensional sorted array in which the search will happen. val : The object value which
    4 min read
  • C# | Array.BinarySearch(Array, Int32, Int32, Object, IComparer) Method
    This method searches for an element which is in a one-dimensional sorted array within a range of elements using a specified IComparer interface. Syntax: public static int BinarySearch(Array arr, int index, int length, Object value, IComparer comparer) Parameters: arr : The sorted one-dimensional Arr
    4 min read
  • Array.BinarySearch(Array, Int32, Int32, Object) Method with examples in C#
    Array.BinarySearch(Array, int32, int32, Object) Method is used to search a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value. It searches only in a specified boundary that the user defi
    4 min read
  • List BinarySearch() Method in C#
    List<T>.BinarySearch(T) 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, ICompar
    9 min read
  • Array.LastIndexOf Method in C# | Set – 2
    Array.LastIndexOf method is used to find the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array. It starts the search from the last element of an array. It returns the index of the element that contains the specified value. There are 6 methods in the over
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences