Binary Search is used to find a given key in a sorted array. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element’s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

Code

        public static int BinarySearch(int[] input, int key)
        {

            int leftPointer = 0;
            int length = input.Length;
            int rightPointer = length - 1;
            int middlePointer = 0;

            while (rightPointer > leftPointer)
            {
                middlePointer = (rightPointer + leftPointer) / 2;

                if (input[middlePointer] < key)
                {
                    leftPointer = leftPointer + 1;
                }
                else if (input[middlePointer] > key)
                {
                    rightPointer = rightPointer - 1;
                }
                else
                {
                    return middlePointer;
                }
            }
            return -1;
        }