Is this a possible program? My teacher gave it to us and maybe she meant linear search -
Write a class that stores names of cities in a single dimensional array of size 5 and using
binary search technique check whether a given name of the city is present in the array
or not.
Answers
HII Freind BYE Freind
Program using Binary Search technique :
import java.util.*;
public class MyClass {
public static void main(String []args)
{
Scanner Sc = new Scanner(System.in);
System.out.print("Enter number of cities you want to store in the array : ");
int n = Sc.nextInt();
String[] arr = new String[n];
System.out.print("Enter " + n + " cities name\n");
for(int i = 0 ; i < n ; i++)
{
arr[i] = Sc.next();
}
System.out.print("Enter city to searched : ");
String x = Sc.next();
int left = 0, right = n - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
int result = x.compareTo(arr[mid]);
if (result == 0)
{
System.out.print("City found ");
break;
}
if (result > 0)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
if(left > right)
{
System.out.print("City not found");
}
}
}