Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help figuring this out please. Problem Statement -Create a class BinarySear

ID: 3910730 • Letter: N

Question

Need help figuring this out please.

Problem Statement

-Create a class BinarySearch
-Create main method.
(Declare the limit and array inside main)
-Read the array limit from user.
-Read the array elements from user (Ask the user to enter a sorted array i.e
Array[0]<Array[1]<Array[2] and so on )
-Now call method Boolean Bin_Search(Array[],limit)
-if the method Bin_Search(Array[],limit) returns true then print Element is found. Otherwise print not found.


Outside main define method Boolean Bin_Search(Array[],limit)
-Read the value to search from the user and store it in a variable say Key.
-Declare two integer variables upper and lower. Set upper to limit and lower to 0.
-Declare a for loop from 0 to limit
Check the following conditions inside loop.
-Calculate mid (middle index )of the array using lower and upper.
If a[mid] is the key element
   Print Position=mid+1
   Return true.
if the key element is <array[mid]
   Scan the left portion of the array, i.e from 0 to mid.
Otherwise
   Scan the right portion of the array from mid to limit.
If not found return false.



Example:

Array: 10, 20, 30, 40, 50, 60
Key=10.
First, mid=(0+5)/2 =2 (int)

Array[mid]== 30 which is greater than the key(10), so we need to search the left portion of the array.

Second mid= (0+2)/2 =1
Array[mid]=20 which is again greater than the key.

Third mid= (0+1)/2=0
Array[mid]=10 which is the key; so the element is found at index 0 and position 1.

Explanation / Answer

Code:

import java.util.*;
public class BinarySearch{
  
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int limit;
System.out.println("Enter limit: ");
limit = sc.nextInt();
int arr[] = new int[limit];
System.out.println("Enter elements in the array in ascending order");
for(int i=0;i<limit;i++){
System.out.println("Enter number at position: "+i+": ");
arr[i] = sc.nextInt();
}
boolean result = Bin_Search(arr,limit,sc);
if(result==true){
System.out.println("Found");
}
else{
System.out.println("Not Found");
}
  
  
}
private static boolean Bin_Search(int arr[],int limit,Scanner sc){
System.out.println("Enter element to be searched: ");

int key = sc.nextInt();
int upper=limit,lower=0;
while(upper>=lower){
int mid = (upper+lower)/2;
if(arr[mid]>key){
upper = mid-1;
}
else if(arr[mid]<key){
lower = mid+1;
}
else if(arr[mid]==key){
return true;
}

}
return false;
}
}

Sample Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote