Question 4



Define a class to search for a value input by the user from the list of values given below. If it is found display the message "Search successful", otherwise display the message "Search element not found” using Binary search technique. 
5.6,11.5,20.8,35.4,43.1, 52.4, 66.6, 78.9, 80.0, 95.5. 
        

Solution:

,
 
import java.util.Scanner;
public class BinarySearch 
{
public static void main(String[] args) 
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();
double[] values = new double[n];
System.out.println("Enter the sorted elements of the array:");
for (int i = 0; i < n; i++) {
values[i] = sc.nextDouble();
}
System.out.print("Enter the value to search: ");
double searchValue = sc.nextDouble();
int low = 0;
int high = n - 1;
boolean found = false;
while (low <= high) 
{
int mid = (low + high) / 2;
if (values[mid] == searchValue) 
{
    found = true;
    break;
} 
else if (values[mid] < searchValue) 
{
    low = mid + 1;
} 
else 
{
    high = mid - 1;
}
}
if (found) {
System.out.println("Search successful");
} else {
System.out.println("Search element not found");
}
}
}

                                                                  


                                            



Reach Us

SERVICES

  • ACADEMIC
  • ON-LINE PREPARATION
  • FOUNDATION & CRASH COURSES

CONTACT

B-54, Krishna Bhawan, Parag Narain Road, Near Butler Palace Colony Lucknow
Contact:+918081967119