IN JAVA Write a BinarySearchEvaluator class, with the following specifications:
ID: 3788686 • Letter: I
Question
IN JAVA
Write a BinarySearchEvaluator class, with the following specifications:
• Member variables array and size, where array is an array of integers arranged in sorted order (smallest to largest), and size is the the size of the array
• Member variable numCalls, initialized to 0, which keeps track of the number of times the binarySearch method is called
• Member methods: • constructor: takes argument for size, creates array to hold the specified number of values; populates array with random increasing values between 1 and size * 10 • binarySearch: finds the value specified in its first argument and increments numCalls each time it is called • reset: sets numCalls back to 0 and repopulates array • getNum: returns value of numCalls • main method to test the others; should run algorithm several times, using randomly generated values to search for, and reports: • whether or not search for particular value was successful • value of numCalls at the end of each search cycle
Explanation / Answer
import java.util.*;
class BinarySearchEvaluator
{
int arr[];
int size, numCalls;
BinarySearchEvaluator(int s)
{
size=s;
arr= new int[size];
numCalls=0;
Random rand=new Random();
int r, min=1;
for(int i=0; i<size;i++)
{
r= rand.nextInt((size*10 - min) + 1) + min;
arr[i]=r;
min=r;
}
}
public int binarySearch(int val)
{
numCalls++;
int s = 0;
int e = size - 1;
while (s <= e) {
int mid = (s + e) / 2;
if (val == arr[mid]) {
return mid;
}
if (val < arr[mid]) {
e = mid - 1;
} else {
s = mid + 1;
}
}
return -1;
}
public void reset()
{
numCalls=0;
}
public int getNum()
{
return numCalls;
}
void displayArray()
{
for(int i=0; i<size;i++)
{
System.out.print(arr[i]+" ");
}
}
public static void main(String a[])
{
BinarySearchEvaluator bs = new BinarySearchEvaluator(10);
System.out.println("Found 5: "+bs.binarySearch(5)); // return index of element of found otherwise -1
System.out.println("Found 10: "+bs.binarySearch(10));
System.out.println("Found 15: "+bs.binarySearch(15));
System.out.println("Found 100: "+bs.binarySearch(100));
System.out.println("Number of Calls: "+bs.getNum());
bs.displayArray();
}
}