Writing a binary search algorithm in C#
Binary search requires that an array be sorted first before searching for the value. The reasoning behind this is that binary search doesn’t visit all the values within the array, but instead will find the midpoint value, sectioning the array into values to the left or right of the midpoint, continually splitting the array in half to narrow down the search. If the value is higher than the midpoint, the algorithm narrows the search to values to the right of the midpoint, known as the upper half, and to the left if it’s lower, known as the lower half. There is also the possibility that the value could be the midpoint. To calculate the midpoint, we’ll need the beginning index and the last index of the area being searched within the array, which will be the whole array at first. The following example shows this calculation:
int[] testArray = {-4, 0, 7, 13, 20, 55, 80}; int lowerHalfIndex = 0; int upperHalfIndex = testArray...