
Code Plain Text:
// Fig. 19.3: BinarySearchTest.java
// Use binary search to locate an item in an array.
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Scanner;
public class BinarySearchTest {
// perform a binary search on the data
public static int binarySearch(int[] data, int key) {
int low = 0; // low end of the search area
int high = data.length - 1; // high end of the search area
int middle = (low + high + 1) / 2; // middle element
int location = -1; // return value; -1 if not found
do { // loop to search for element
// print remaining elements of array
System.out.print(remainingElements(data, low, high));
// output spaces for alignment
for (int i = 0; i < middle; i++) {
System.out.print(" ");
}
System.out.println(" * "); // indicate current middle
// if the element is found at the middle
if (key == data[middle]) {
location = middle; // location is the current middle
}
else if (key < data[middle]) { // middle element is too high
high = middle - 1; // eliminate the higher half
}
else { // middle element is too low
low = middle + 1; // eliminate the lower half
}
middle = (low + high + 1) / 2; // recalculate the middle
} while ((low <= high) && (location == -1));
return location; // return location of search key
}
// method to output certain values in array
private static String remainingElements(
int[] data, int low, int high) {
StringBuilder temporary = new StringBuilder();
// append spaces for alignment
for (int i = 0; i < low; i++) {
temporary.append(" ");
}
// append elements left in array
for (int i = low; i <= high; i++) {
temporary.append(data[i] + " ");
}
return String.format("%s%n", temporary);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SecureRandom generator = new SecureRandom();
// create array of 15 random integers in sorted order
int[] data = generator.ints(15, 10, 91).sorted().toArray();
System.out.printf("%s%n%n", Arrays.toString(data)); // display array
// get input from user
System.out.print("Please enter an integer value (-1 to quit): ");
int searchInt = input.nextInt();
// repeatedly input an integer; -1 terminates the program
while (searchInt != -1) {
// perform search
int location = binarySearch(data, searchInt);
if (location == -1) { // not found
System.out.printf("%d was not found%n%n", searchInt);
}
else { // found
System.out.printf("%d was found in position %d%n%n",
searchInt, location);
}
// get input from user
System.out.print("Please enter an integer value (-1 to quit): ");
searchInt = input.nextInt();
}
}
}


Trending nowThis is a popular solution!
Step by stepSolved in 2 steps with 3 images

- public int binarySearch(int[]array, int num) {int low = 0;//low rangeint high = array.length -1; //high range int mid; //mid rangewhile () //while low is less than or equal to high{mid = ; //set middle range to be (low + high) /2if () { //if the array in the middle range = input number//return mid range }elseif () { //if the array in the middle range > input number//set the high value to be the mid value minus 1 }else{//set low value to be mid value plus one } }//return -1 here because that would mean that the number is not found in the loop}arrow_forwardMethod Details getCountInRange public static int getCountInRange(int[] array, int lower, int upper) Returns the number of values in the range defined by lower (inclusive) and upper (inclusive) Parameters: array - integer array lower - lower limit upper - upper limit Returns: Number of values found Throws: java.lang.IllegalArgumentException - if array is null or lower is greater than upper Any error message is fine (e.g., "Invalid parameters(s)")arrow_forwardX40: sum3 Given an array containing three ints, return the sum of all the elements. Examples: sum3({1, 2, 3}) -> 6 sum3({5, 11, 2}) -> 18 Your Answer: 1 public int sum3(int[] nums) 2{ 3 4} Check my answer! Reset Next exercisearrow_forward
- Java Netbeansarrow_forwardQUESTION 1 When defining a Java array, the index range of the array: Must start at 1 Must start at 0 Can be a customized range (from 2 to 5, e.g.) at compilation time Can be a customized range (from 2 to 5, e.g.) at run timearrow_forwardJava - When using an array to do a binary search, what additional requirement is placed on the array?arrow_forward
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY





