RSS

Binary Search in C#

21 Aug

Simple iterative and recursive Binary Search implementations using C#. The int array has to be sorted before calling both methods.

public static int? IterativeBinarySearch(int[] source, int value, int left, int right)
{
    while (left <= right)
    {
        int middle = (left + right) / 2;

        if (source[middle] == value)
            return middle;
        else if (source[middle] > value)
            right = middle - 1;
        else if (source[middle] < value)
            left = middle + 1;
    }
    return null;
}

public static int? RecursiveBinarySearch(int[] source, int value, int left, int right)
{
    if (left <= right)
    {
        int middle = (left + right) / 2;

        if (source[middle] == value)
            return middle;
        else if (source[middle] > value)
            return RecursiveBinarySearch(source, value, left, middle - 1);
        else if (source[middle] < value)
            return RecursiveBinarySearch(source, value, middle + 1, right);
    }
    return null;
}
Advertisements
 
Leave a comment

Posted by on August 21, 2012 in Algorithm, C#

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: