Learn Computer Science programming - C# and C++ Algorithms

 

Binary Search

This is a Divide-and-Conquer search algorithm that works on a sorted array. It works by continuously dividing the array into two halves and keeps searching for an item until it finds it.
Code
c_binary_search.zip
File Size: 22 kb
File Type: zip
Download File

using System;

class BinarySearch
{
    static void Main()
    {
        int[] array = new int[] { 5, 7, 10, 22, 32, 41, 50 };
        int left = 0;
        int right = array.Length - 1;
        Console.Write("Enter number to find in the array { 5, 7, 10, 22, 32, 41, 50 }:");
        string inputString = Console.ReadLine();
        int number = int.Parse(inputString);
        int index = -1;
        bool found = false;

        while (!found && left <= right)
        {
            int middle = (right + left) / 2;

            if (array[middle] == number)
            {
                index = middle;
                found = true;
            }
            else if (number > array[middle])
            {
                left = middle + 1;
            }
            else // number < middle
            {
                right = middle - 1;
            }
        }

        if (found)
        {
            Console.WriteLine("Number is found at index {0}", index);
        }
        else
        {
            Console.WriteLine("Number not found");
        }

        Console.Write("Press Enter...");
        Console.ReadLine();
    }
}