In: Computer Science
Binary Search Algorithm
a.) Create a Java application that utilizes the "Binary Search Algorithm" presented in chapter 19 (NOT Java's pre-built binarySearch() method from imported Java library) to search for an integer in a random array of size 30 in the range of 0 to 1000 inclusive. You should use Java's random number generator to randomize the numbers in your array.
b.) The application's main() method should display unsorted array and sorted array, prompt user for a search key, allow user to enter a search value from the keyboard, read in the user's keyboard entry, then perform binary search for the search key in the array after the array is sorted, then inform the user of the search result in the console by displaying a message indicating whether or not the value is found, if found, also display its index in the array. Note:binarySearch() for a value in an array require the array to be sorted first, before searching for any value in the array.
Here is your program. Hope it helps. upvoting would be really helpfu Thanks :)
import java.io.*;
import java.util.Random;
import java.util.Arrays;
import java.util.*;
public class hello{
public static void main(String[] args) {
int up =100;
Random rd = new Random(); // creating Random object
int[] arr = new int[30];
int low = 0;
int high = 1000,result = 0;
for (int i = 0; i < arr.length; i++) {
arr[i] = rd.nextInt(high-low) + low;
// storing random integers in an array
// printing each array element
}
System.out.println("unSorted array is ");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
Arrays.sort(arr);
System.out.println("Sorted array is ");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);}
Scanner sc = new Scanner(System.in);
int n;
System.out.println("Enter Search Element");
n = sc.nextInt();
int mid = 0,l = 0,hi = 29,k=0;
while(l<=hi)
{
mid = (l+hi)/2;
if(arr[mid] == n)
{
k = 1;
break;
}
else if(arr[mid]<n)
{
l = mid+1;
}
else if(arr[mid]>n)
hi = mid-1;
}
if(k==1)
System.out.println("Success");
else
System.out.println("Fail");
}
}