Binary Search Implement a binanry search program with the following requirements
ID: 3563535 • Letter: B
Question
Binary Search
Implement a binanry search program with the following requirements: Create a generic class called BinarySearcher for executing binary searches through an array. Finds a value in a sorted array, using the binary search algorithm. The binary search method has one parameter (the value to search) and returns the index at which the value occurs, or -1 if it does not occur in the array. The class BinarySearcher has a private data member as an array, a constructor, and the binary search method. Create a class called SelectionSort. The class has a static method that will sort the passing array as an argument using a selection sort algorithm. The sort method should be able to sort any objects in ascending or descending order. Write a test driver to search the following: An faculty object. Initialize an array of faculty objects. An integer number. A set of integer number is entered from the user.Explanation / Answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// Simple Program For Binary Search In Java Using Class
public class BinarySearchExample {
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of elements");
int num = Integer.parseInt(br.readLine());
int a[] = new int[num];
System.out.println("Please enter");
for (int i = 0; i < num; i++) {
a[i] = Integer.parseInt(br.readLine());
}
System.out.println("Enter the element to search");
int find = Integer.parseInt(br.readLine());
int index = search(a, find);
if (index != -1) {
System.out.println("Element found : " + index);
} else {
System.out.println("Element not found");
}
}
public static int search(int ar[], int find) {
int start = 0;
int end = ar.length - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (ar[mid] == find) {
return mid;
} else if (ar[mid] < find) {
start = mid + 1;
} else if (ar[mid] > find) {
end = mid - 1;
}
}
return -1;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.