Example of Binary Search in C#

Following is the example of binary search –

/// <summary>

/// Example of Binary Search.

/// </summary>

/// <param name=”Value”></param>

/// <returns></returns>

public int FindTheValuePosition(int Value)

{

    //Sorted Array

    int[] myArray = new int[] { 1, 2, 4, 6, 10, 14, 15, 19, 20, 34, 36, 38, 40, 42, 50, 55, 60, 61, 62, 63, 67, 70, 78, 80, 82, 84, 86, 88, 90, 92, 93, 99, 101, 105, 107, 110, 115 };

 

 

    int FirstIndex = 0;

    int LastIndex = myArray.Length;

 

    //Check that value is in range of array.

    if (Value > myArray[myArray.Length – 1])

        return -1;

 

    if (Value < myArray[0])

        return -1;

 

    while (FirstIndex <= LastIndex)

    {

        int Mid = (FirstIndex + LastIndex) / 2;

        if (Value > myArray[Mid])

        {

            FirstIndex = Mid + 1;

        }

        else if (Value < myArray[Mid])

        {

            LastIndex = Mid – 1;

        }

        else

        {

            return Mid;

        }

    }

    return -1; //Not Found

}

Advertisements

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: