Binary Search Array in C#

In this article I will explain that how to Binary Search in Array.
  • 6491

This C# example program uses the Array Binary Search method. It searches an array.sorting and searching algorithms enabled in this program. The Array.BinarySearch method has one version that accepts a type parameter, which you can specify in angle brackets.

namespace demo_array

{

    class Program

    {     

        static void Main(string[] args)

        {

            string[] arr = new string[5];

            arr[0] = "abc";

            arr[1] = "pqr";

            arr[2] = "ajay";

            arr[3] = "Raju";

            arr[4] = "Manish";

            int i;

            Array.Sort(arr);

            for (i = 0; i < arr.Length; i++)

            {

                Console.WriteLine("The item " + arr[i] + " found at " + i);

            }

            // Find an item        

            object name = "Raju";

            int nameIndex = Array.BinarySearch(arr, name);

            if (nameIndex >= 0)

                Console.WriteLine("<br>"+"Item was at " + nameIndex.ToString() + "th position");

            else

                Console.WriteLine("<br>"+"Item not found");

            Console.ReadKey();        

        }

    }

}

Output

dearch_binary.jpg

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.