Friday, November 29, 2013

P3C4: C Sharp Program for Binary search

using System;

public class Program_Binary_Search
{
    int binary_search(int[] a, int size, int item)
    {
        int first = 0, last = size - 1, middle;
        while (first <= last)
        {
            middle = (first + last) / 2;

            if (item == a[middle])
                return middle;
            else if (item < a[middle])
                last = middle - 1;
            else
                first = middle + 1;
        }
        return -1;
    }
     
    public static void Main()
    {
     
        int[] b = new int[] {2,4,5,7,8,9,12,15};
        int size=8, item;
     
        Console.WriteLine("Enter a number to search: ");
        item =Convert.ToInt32(Console.ReadLine());


        Program_Binary_Search pbs = new Program_Binary_Search();
        int p = pbs.binary_search(b, size, item);
     
        if (p ==-1)
            Console.WriteLine("\n{0} is not present in the array", item);
        else
            Console.WriteLine("\n{0} is present in the array at index no: {1}", item, p);

        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();
    }
}

OUTPUT

Enter a number to search:
7

7 is present in the array at index no: 3

Press any key to exit...

No comments:

Post a Comment