How to Search Array using Binary Search in C# ?

If you are working on arrays in C# and want to search the array using the Binary Search algorithm , you can use the Binary Search static method defined in the Array class.

The Array.BinarySearch method lets the user search the one dimensional array for a specified element . Note that the Array should be sorted for the Binary Search method to work fine.

How to Search Array using Binary Search in C# ?

Below is the sample code snippet demonstrating the usage of the Array.BinarySearch method to search the array elements.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DeveloperPublishConsoleApp
{
    internal class Program
    {
        private delegate void result();

        private static void Main(string[] args)
        {
            string[] inputStr = { "Java", "CSharp", "Xamarin", "Windows", "android", "iOS" };
            Console.WriteLine("Input List");
            Console.WriteLine("----------");
            foreach (string input in inputStr)
            {
                Console.WriteLine(input);
            }
            // Sort the Array
            Array.Sort(inputStr);

            Console.WriteLine("Sorted List");
            Console.WriteLine("-----------");
            foreach (string input in inputStr)
            {
                Console.WriteLine(input);
            }
            Console.WriteLine("Binary Search for Xamarin");
            Console.WriteLine("-------------------------");
            int index = Array.BinarySearch(inputStr, "Xamarin");
            Console.WriteLine("Xamarin is found at " + index);
            Console.ReadLine();
        }
    }
}

Output

image

Note that the Array.BinarySearch method does not support the searching of arrays that contain negative indexes. If the input array does not contain the value that you are searching for ,then the method returns a negative value . If the search is found , the result will be the index where the search value is found within the array.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...