Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please trace this java Binary search code! Show steps and results... // Binary S

ID: 3772864 • Letter: P

Question

Please trace this java Binary search code! Show steps and results...

// Binary Search

import java.util.Scanner;

public class BinSearch {

public static void main(String[] args) {

final int SIZE = 10;

int [] x = {-13, 2, 3, 19, 29, 37, 44, 47, 99, 999};

   Scanner input = new Scanner(System.in);

   System.out.println("Enter key: ");

int key = input.nextInt();

int low = 0, high = x.length-1;

int found = -1;

while (high >= low) {

      int midIndex = (high + low) / 2;

      if (x[midIndex] == key) {

       found = midIndex;

       break;

      }

      else if (key < x[midIndex]) {

       high = midIndex - 1;

      }

      else {

       low = midIndex + 1;

      }

   }

if (found == -1) {

      System.out.println("Key not found");

   }

else {

      System.out.println("Key found at index " + found);

   }

}

}

Explanation / Answer

1. suppose we want to search key value 47
2. low =0 and high=9
3. loop starts since high>=low
4. midindex=9+0/2 = 4
5. midindex!=key
6. key > 29
7. low=4+1=5
8. loop iterates high >= low
9. midindex=5+9/2=7
10 x[midindex]==7
11. found =7
12. loop breaks
13.Message displayed- Key found at index 7