Visual C# – RecursiveBinarySearch

RecursiveBinarySearch1RecursiveBinarySearch2RecursiveBinarySearch3


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RecursiveBinarySearch
{
    class RecursiveBinarySearch
    {
        static void Main(string[] args)
        {
            int searchInt;
            int position;

            RecursiveBinaryArray searchArray = new RecursiveBinaryArray(25);
            Console.WriteLine(searchArray);

            do
            {
               Console.WriteLine("Please enter an integer value (-1 to quit): ");
               searchInt = Convert.ToInt32(Console.ReadLine());
               Console.WriteLine();

               position = searchArray.BinarySearch(searchInt, 0, 24);

               if (position == -1)
                  Console.WriteLine("The integer {0} was not found.\n", searchInt);
               else
                  Console.WriteLine("The integer {0} was found in index position {1}.\n",
                      searchInt, position);
            } while (searchInt != -1);
        }
    }
}


using System;

class RecursiveBinaryArray
{
    private int[] data;
    private static Random generator = new Random();

    public RecursiveBinaryArray(int size)
    {
        data = new int[size];

        for (int i = 0; i < size; i++)
            data[i] = generator.Next(10, 100);
        Array.Sort(data);
    }

    public int BinarySearch(int key, int low, int high)
    {
       int mid = (low + high + 1) / 2;
       Console.WriteLine(RemainingElemensts(low, high));

       for (int i = 0; i < mid; i++)
          Console.Write("   ");
       Console.WriteLine("*");

        if (low > high)
        {
            return -1;
        }
        else
        {
            if (key == data[mid])
            {
                return mid;
            }
            else if (key > data[mid])
            {
                return BinarySearch(key, mid + 1, high);
            }
            else
            {
                return BinarySearch(key, low, mid - 1);
            }
        }
    }

    public string RemainingElemensts(int low, int high)
    {
        string temp = string.Empty;

        for (int i = 0; i < low; i++)
            temp += "   ";
        for (int i = low; i <= high; i++)
            temp += data[i] + " ";
        temp += "\n";
        return temp;
    }

    public override string ToString()
    {
        return RemainingElemensts(0, data.Length - 1);
    }
}