Page 336 - ComputerScience_Class_11
P. 336

Now, 8 > ar[2], i.e., 6.
                      So, it has been concluded that the element to be searched is in the right half of the array.
                      Now, min = mid + 1 = 2 + 1 = 3
              Step 2:  Repeat the above step.

                              Position  or index   0           1           2          3           4
                                    Ar             1           4           6          8          10
                                                                                     min         Max
                                                                                     mid
              Middle element is 8 as (3 + 4) / 2 = 7 / 2 = 2 (taking only the integer part)

              Now, 8 == ar[3], i.e., 8.
              Thus, the searched element is found and the loop breaks.
              Since the array is already sorted, the binary search technique is faster than the linear search technique.


                Program 9      Write a Java program to input “n” names in an array and a name to search for and print
                               whether the name is present in the array or not. (Use the binary search technique)
                 1       import java.util.*;

                 2       class Binary_search
                 3       {

                 4           public static void main(String args[])
                 5           {

                 6               Scanner sc= new Scanner(System.in);
                 7               System.out.print("How many names you want to enter? ");

                 8               int n = sc.nextInt();
                 9               String ar[]=new String[n];

                10               int i, pos=-1, min=0, mid=0, max=n;
                11               String ns;

                12               for (i=0; i<n; i++)
                13               {
                14                   System.out.print("Enter a name: ");

                15                   ar[i] =sc.next();

                16               }
                17               System.out.print("Enter a name to search: ");
                18               ns=sc.next();

                19               while(min<max)
                20               {

                21                   mid=(min+max)/2;
                22                   if(ar[mid].equalsIgnoreCase(ns))




                  334  Touchpad Computer Science (Ver. 3.0)-XI
   331   332   333   334   335   336   337   338   339   340   341