X439: Binary Search (non-recursive)

Complete the following binary search method. Find the number num in the array array. Return -1 if the number is not found. You may assume the array is properly ordered.

Examples:

binarySearch({1,4,7},7) -> 2
binarySearch({2,6,6,8,80},6) -> 2

Your Answer:

x
 
1
public int binarySearch(int[]array, int num) {
2
  int low = 0;
3
  //low range
4
  int high = array.length -1; //high range 
5
  int mid; //mid range
6
  while ()  //while low is less than or equal to high
7
  {
8
    mid = ; //set middle range to be (low + high) /2
9
    if () { //if the array in the middle range = input number
10
      //return mid range
11
12
    }
13
    else
14
      if () { //if the array in the middle range > input number
15
        //set the high value to be the mid value minus 1
16
17
      }
18
      else
19
      {
20
        //set low value to be mid value plus one
21
22
      }     
23
  }
24
  //return -1 here because that would mean that the number is not found in the loop
25
}
26

Feedback

Your feedback will appear here when you check your answer.