Implement Binary Search - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Search

Description

Implement Binary Search

Demo Code

using System;/* w  w  w. j  av  a2 s. c  om*/
class BinarySearcher
{
   //Search for the key value in the arr array
   //using the binary search algorithm.
   public static int BinarySearch (int key, int[] arr)
   {
      int low = 0;
      int high = arr.Length - 1;
      int middle;
      while (low <= high)
      {
         middle = (low + high) / 2;
         if (key > arr[middle])
            low = middle + 1;
         else if (key < arr[middle])
         high = middle - 1;
         else
            return middle;
         }
         return -1;
      }
      public static void PrintArray(int low, int middle, int high, int [] arr)
      {
         for (int i = 0; i <= high; i++)
         {
            if (i < low)
            {
               Console.Write("    ");
            }
            else
            {
               if (i == middle)
                  Console.Write("{0,2}m ", arr[i]);
               else
                  Console.Write("{0,2}  ", arr[i]);
            }
         }
         Console.WriteLine();
      }
         public static void Main()
         {
            int searchKey;
            int searchResult;
            int [] testScores = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38};
            do
            {
               Console.Write("Please enter the test score you would like to locate: ");
               searchKey = Convert.ToInt32(Console.ReadLine());
               searchResult = BinarySearch(searchKey, testScores);
               if (searchResult >= 0)
                  Console.WriteLine("The score was found in position: {0}\n", searchResult);
               else
                  Console.WriteLine("The score was not found\n");
               Console.Write("Would you like to do another search? Y)es N)o ");
            } while (Console.ReadLine().ToUpper() == "Y");
         }
}

Result


Related Tutorials