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