Implement Recursive Binary Search - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Search

Description

Implement Recursive Binary Search

Demo Code

using System;/*from  ww w . j a v a  2s.c  o  m*/
class Searcher
{
   private static int[] arr;
   public static int StartSearch(int[] newArray, int searchKey, int low, int high)
   {
      arr = newArray;
      return BinarySearch(searchKey, low, high);
   }
   public static int BinarySearch(int key, int low, int high)
   {
      if(low > high)
         return -1;
      else
      {
         int mid = (low + high) / 2;
         if(key == arr[mid])
            return mid;
         else if (key < arr[mid])
            return BinarySearch(key, low, mid - 1);
         else
            return BinarySearch(key, mid + 1, high);
      }
   }
}
class Tester
{
      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 = Searcher.StartSearch(testScores, searchKey, 0, 18);
            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