Challenge: Binary Search
We'll cover the following...
Complete the doSearch function so that it implements a binary search, following the pseudo-code below (this pseudo-code was described in the previous article):
Let
min = 0andmax = n - 1.If
max < min, then stop: target is not present in array. Return-1.Compute guess as the average of
maxandmin, rounded down (so that it is an integer).If
array[guess]equalstarget, then stop. You found it! Returnguess.If the guess was too low, that is,
array[guess] < target, then setmin = guess + 1.Otherwise, the guess was too high. Set
max = guess - 1.Go back to step 2.
import java.util.Arrays;import java.lang.Integer;class Solution {// Returns either the index of the location in the array,// or -1 if the array did not contain the targetValuepublic static int doSearch(int[] array, int targetValue) {int min = 0;System.out.println(Arrays.toString(array));int max = array.length - 1;int guess;return -1;}};
Ask