Write a program in java 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 exist". 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}.


THE FOLLOWING PROGRAM SEGMENT SHOWS HOW TO ACCEPT THE YEAR OF GRADUATION FROM SCHOOL AS AN INTEGER VALUE AND PRINT THE SEARCHED YEAR OF GRADUATION IF FOUND OR NOT FROM THE LIST.
import java.util.*;
class Binary
{
    public static void main (String args[])
    {
        Scanner ob = new Scanner (System.in);
        int n[] = {1982, 1987, 1993, 1996,1999, 2003, 2006, 2007, 2009, 2010};
         System.out.println("Enter the graduation year to search");
         int yr = ob.nextInt();
         int l  = 0, h = n.length - 1, idx = -1;
         while( l<= h)
         {
             int mid = (l+h)/2;
             if(n[mid] == yr)
             {
                 idx = mid;
                 break;
                }
                else if(n[mid] < yr)
                {
                    l = mid +1;
                }
                else
                {
                    h = mid -1;
                }
            }
            if(idx == -1)
            {
                 System.out.println("Record does not exist");
                }
                else
                {
                     System.out.println("Record exists");
                    }
                }
            }

The above program is compiled and is without any error.

Hope you guys found it helpful.

Please share it with your friends and comment down in the comment section below.

Follow https://askrisfor.blogspot.com/ for more such updates.

Visit us again.

Thank you!!

Comments

Popular Posts