Sponsored Ad

Monday, January 17, 2011

Find an Element using Binary Search in an Array - C#

Binary Search is possible in an array. You do not have to write the customer code to search an element. C# provides a inbuilt function to search an element using the binary search. The sample example of binary search is given below.

Find an Element using Binary Search in an Array - C#

using System;

namespace MyApp
{
    class clsBinarySearch
    {
        static void Main(string[] args)
        {
            string[] strArray = { "A", "B", "C", "D", "E", "F", "G", "H", "I"};
            Console.WriteLine("Source Array: ");
            foreach(string str in strArray)
                Console.Write(str + " ");

            Console.WriteLine("");
           int intIndex = Array.BinarySearch(strArray, "E");
           Console.WriteLine("Element 'E' Found at: " + intIndex);
            intIndex = Array.BinarySearch(strArray, "e");
           Console.WriteLine("Element 'e' Found at: " + intIndex);

            Console.ReadLine();
          }         
    }
}

No comments:

Post a Comment

Sponsored Ad

Development Updates