// Takes in an array of integers, the value to search for and the lowest and // highest array indexes of the array. Returns the index of the found value or // returns -1 if no item is found. public int BinarySearch(int[] arNumbers, int searchValue) { int min = 0; int max = arNumbers.Length - 1; while (max >= min) { int midpoint = (max - min) / 2 + min; if (searchValue > arNumbers[midpoint]) { min = midpoint + 1; } else if (searchValue < arNumbers[midpoint]) { max = midpoint - 1; } else { return midpoint; } } return -1; }
Posted: March 17, 2023
Return to the snippets listing