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:
C# | Array.BinarySearch(Array, Int32, Int32, Object, IComparer) Method
Next article icon

Array.BinarySearch(Array, Int32, Int32, Object) Method with examples in C#

Last Updated : 24 Jan, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Syntax:

  public static int BinarySearch(Array array, int index, int length, object value);  

Parameters:

  • array: It is 1-D array in which we have to search for an element.
  • index: It is the starting index of the range from where you want to start the search.
  • length: It is the length of the range in which we want to search.
  • value: It is the value which we to search for.

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

  • If the value is not found and value is less than one or more elements in the array, the negative number returned is the bitwise complement of the index of the first element that is larger than value.
  • If the value is not found and value is greater than all elements in the array, 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 value is present in the array.

Exceptions:

  • ArgumentNullException: If the array is null.
  • RankException: If array is multidimensional.
  • ArgumentOutOfRangeException: If the range is less than lower bound OR length is less than 0.
  • ArgumentException: If the index and length do not specify the valid range in array OR value is of the type that is not compatible with the elements of the array.
  • InvalidOperationException: If value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.

Below programs illustrate the above-discussed method:

Example 1:




// C# Program to illustrate the use of 
// Array.BinarySearch(Array, Int32, 
// Int32, Object) Method
using System;
using System.IO;
  
class GFG {
      
    // Main Method
    static void Main()
    {
        // initializing the integer array
        int[] intArr = {42, 5, 7, 12, 56, 1, 32};
          
        // sorts the intArray as it must be 
        // sorted before using method
        Array.Sort(intArr);
          
        // printing the sorted array
        foreach(int i in intArr) Console.Write(i + " "
                                              + "\n");
                                                
        // intArr is the array we want to find
        // and 1 is the starting index
        // of the range to search. 5 is the 
        // length of the range to search.
        // 32 is the object to search
        int index = Array.BinarySearch(intArr, 1, 5, 32);
          
        if (index >= 0) {
              
            // if the element is found it 
            // returns the index of the element
            Console.Write("Index: " + index);
        }
          
        else {
              
            // if the element is not
            // present in the array or
            // if it is not in the 
            // specified range it prints this
            Console.Write("Element is not found");
        }
    }
}
 
 
Output:
  1   5   7   12   32   42   56   Index: 4  

Example 2: If the element is not in the array it prints a negative value or if it is out of the range.




// C# Program to illustrate the use of 
// Array.BinarySearch(Array, Int32, 
// Int32, Object) Method
using System;
using System.IO;
  
class GFG {
      
    // Main Method
    static void Main()
    {
        // initializing the integer array
        int[] intArr = {42, 5, 7, 12,
                          56, 1, 32};
                            
        // sorts the intArray as it must be 
        // sorted before using Method
        Array.Sort(intArr);
          
        // printing the sorted array
        foreach(int i in intArr) Console.Write(i + " "
                                              + "\n");
                                                
        // intArr is the array we want to
        // find. and 1 is the starting
        // index of the range to search. 5 is 
        // the length of the range to search
        // 44 is the object to search
        int index = Array.BinarySearch(intArr, 1, 5, 44);
          
        // as the element is not present
        // it prints a negative value.
        Console.Write("Index :" + index);
    }
}
 
 
Output:
  1   5   7   12   32   42   56   Index :-7  

Reference:

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


Next Article
C# | Array.BinarySearch(Array, Int32, Int32, Object, IComparer) Method

K

Krishna_Sai_Ketha
Improve
Article Tags :
  • C#

Similar Reads

  • 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
  • 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
  • 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
  • How to use Array.BinarySearch() Method in C# | Set -2
    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
    12 min read
  • Array.GetValue() Method in C# with Examples | Set – 4
    Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32)Array.GetValue(Int64, Int64)Array.GetValue(Int32)Array.GetValue(Int64)Array.GetValue(
    5 min read
  • Array.GetValue() Method in C# with Examples | Set – 2
    Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32) Array.GetValue(Int64, Int64) Array.GetValue(Int32) Array.GetValue(Int64) Array.GetVa
    3 min read
  • Array.GetValue() Method in C# with Examples | Set - 1
    Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32) Array.GetValue(Int64, Int64) Array.GetValue(Int32) Array.GetValue(Int64) Array.GetVa
    4 min read
  • Array.GetValue() Method in C# with Examples | Set – 3
    Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32)Array.GetValue(Int64, Int64)Array.GetValue(Int32)Array.GetValue(Int64)Array.GetValue(
    5 min read
  • BitArray.LeftShift() Method in C# with Examples
    BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.LeftShift(Int32) method is used to shift the bits of the bit array to the left by one positi
    2 min read
  • Int32.Equals Method in C# with Examples
    Int32.Equals() Method is used to get a value which indicates whether the current instance is equal to a specified object or Int32 or not. There are two methods in the overload list of this method as follows: Equals(Int32) Method Equals(Object) Method Int32.Equals(Int32) This method is used to return
    3 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