Write a Program to Accept the Year of Graduation from School as an Integer Value From, the User. Using the Binary Search Technique on the Sorted Array of Integers Given Below.
Advertisements
प्रश्न
Write a program to accept the year of graduation from school as an integer value from, the user. Using the Binary Search technique on the sorted array of integers given below.
Output the message “Record exists” If the value input is located in the array. If not, output the message “Record does not exist”.
{1982, 1987, 1993, 1996. 1999, 2003, 2006, 2007, 2009, 2010}.
Advertisements
उत्तर
import java.io.*;
class Search
{
public static void main ( ) throws IOException
{
int[ ] year={1982, 1987, 1993, 1996. 1999, 2003, 2006, 2007, 2009, 2010};
InputStreamReader IR = new InputStreamReader (System.in);
BufferedReader br=new BufferedReader (IR);
System.out.println("Enter year of Graduation :");
int y = Integer.parseInt (br. readLine ());
int beg, mid, end, pos;
beg = 0;
end = 9;
pos = -1;
while (beg < = end && pos == -1)
{
mid = (beg + end)/2;
if (y == year [mid])
pos = mid;
else
if (y > year [mid])
beg = mid + 1;
else
end = mid - 1;
}
if (pos ! = -1)
System.out.println ("Record exists");
else
System.out.println ("Record does not exist");
}
}
