Array.Binarysearch(Array, Int32, Int32, Object) Method With Examples In C#

In this guide, you will discover the functionality of the "Array.BinarySearch(Array, Int32, Int32, Object)" method in C#, including its syntax, input parameters, and a practical illustration.

What is Array.BinarySearch Method?

A binary search can be performed on a one-dimensional, arranged array in C# by employing the "Array.BinarySearch(Array, Int32, Int32, Object)" function found within the Array class. This method proves beneficial when seeking a specific element within a designated array range. It is imperative to have the array sorted for the binary search algorithm to execute accurately. In cases where the array is not sorted, the outcomes are unpredictable.

The binary search algorithm is a highly effective method that consistently splits the search range in half. When dealing with extensive datasets, it outperforms a linear search due to its time complexity of O(logn).

To conduct the comparison, every item within the array needs to either offer a unique IComparer implementation or belong to a category that supports the IComparable interface.

Syntax:

It has the following syntax:

Example

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

Parameters:

array: The organized, single-dimensional array that will undergo searching.

index: It represents the initial position within the range that will be searched.

size: The quantity of items within the scope of the search.

value: The item that needs to be located within the specified range.

Return Value:

  • If the searched object is found at index 'i', the method returns 'i'.
  • If the searched object is not found, the method returns a negative number '-(x + 1)', where 'x' is the index of the next element larger than the searched object, or if there are no larger elements, the bitwise complement of the length of the array.
  • 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, raise ArgumentNullException .
  • RankException: If the array is multidimensional.
  • ArgumentOutOfRangeException: An ArgumentOutOfRangeException occurs when the range is less than the lower bound or the length is less than zero.
  • ArgumentException: When a value is of a type incompatible with the array's elements or when the index and length fail to indicate the array's valid range.
  • InvalidOperationException: An invalid operation exception will occur if an element found during the Search does not implement the IComparable interface and the Value does not.
  • Example:

Let's consider a scenario to demonstrate the Array.BinarySearch function in C#.

Example

using System;
class Demo
{
    static void Main()
    {
        // An example of a sorted integer array for BinarySearch
        int[] num_bers = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
        //Value to search for
        int target_Value = 11;
        // Perform a binary search throughout the whole array.
        int fullArray_Index = Array.BinarySearch(num_bers, target_Value);
        // Perform binary Search within a subrange of the array
        int start_Index = 0;
        int length = 7; 
        //Search in the first 7 elements
        int subrange_Index = Array.BinarySearch(num_bers, start_Index, length, target_Value);
        //Search for a value that is not present in the array
        int notIn_ArrayValue = 8;
        int notIn_ArrayIndex = Array.BinarySearch(num_bers, notIn_ArrayValue);
        PrintResult("Full Array Search\n", fullArray_Index, target_Value);
        PrintResult("Subrange Search\n", subrange_Index, target_Value);
        PrintResult("Not in Array Search\n", notIn_ArrayIndex, notIn_ArrayValue);
    }
    static void PrintResult(string searchType, int index, int value)
    {
        if (index >= 0)
        {
            Console.WriteLine($"{searchType}Value {value} found at index {index}");
        }
        else
        {
            int insertionPoint = ~index;
            Console.WriteLine($"{searchType}Value {value} not found. The next larger element is at index {insertionPoint}");
        }
        Console.WriteLine();
    }
}

Output:

Output

Full Array Search
Value 11 found at index 5
Subrange Search
Value 11 found at index 5
Not in Array Search
Value 8 not found. The next larger element is at index 4

Explanation:

  1. Array Initialization

An array named num_bers is initialized with integers sorted in ascending order.

  1. Search Criteria

The desired value to look for is 11.

  1. Binary Search

Binary searches are executed in two situations using the "Array.BinarySearch" method:

  • The first one searches for target_Value throughout the entire array.
  • The second one searches for target_Value just in the first seven elements.
  1. Search for a Value Not in the Array

The function is invoked to locate a value (notIn_ArrayValue) that is absent from the array.

  1. Displaying the Outcome

A supporting function called PrintResult is utilized to display the outcomes of each scenario.

It displays the status of finding the Value and offers details on the subsequent greater element if not found.

This illustration showcases situations where the desired value is sought within a subset of the array, not discovered, and successfully found. Subsequently, it displays informative messages pertaining to the outcomes.

Input Required

This code uses input(). Please provide values below: