How the binary search code works


Discussion:

Q: Examine the below binary search program. Write a Word or text document detailing how the binary search code works.

public class BinSearch {

public static void main(String[] args) {
int max = 20;
int[] ints1 = new int[max];

// Construct a Sorted List

for (int i = 0; i < ints1.length; ++i) {
ints1[i] = i + 2;
System.out.print("The value at array location: " + i);
System.out.println(" is: " + ints1[i]);
}
// start
// Binary Search
System.out.println();
int item = 17;
int first = 0;
int last = ints1.length - 1;
int mid = 0;

while (first < last) {
System.out.println("Looking at positions " + first + " through " + last);
mid = (first + last) / 2;
System.out.println("Checking position " + mid);
if (ints1[mid] == item) {
System.out.println("The item was found: " + item);
System.exit(0);
} else
if (ints1[mid] > item) {
last = --mid;
} else {
first = ++mid;
}
} //end while
//end
System.out.println("The item was not found: " + item);
}
}

Solution Preview :

Prepared by a verified Expert
Data Structure & Algorithms: How the binary search code works
Reference No:- TGS01931841

Now Priced at $20 (50% Discount)

Recommended (99%)

Rated (4.3/5)