Tuesday, 20 December 2016

Binary Search in C#

When the records you are searching through are sorted into order, you can perform a more efficient search than the sequential search to find a value. This search is called a binary search.
To use this search first we need to sort our data in ascending order.

C# Function for Binary Search

int BinarySearchMethod(int value, int[]arr)
        {
            int lower = 0;
            int upper = arr.Length - 1;

            while (lower <= upper)
            {

                int mid = (lower + upper) / 2;
                if (value == arr[mid])
                {
                    return mid;
                }
                else if (value > arr[mid])
                {
                    lower = mid + 1;
                }
                else
                {
                    upper = mid - 1;
                }

            }
            return -1;
        }

If value is found in Array then this above function will return the 'position' of element.

No comments:

Post a Comment