Page 334 - ComputerScience_Class_11
P. 334

The following steps are to be taken in the linear search technique:
              Step 1:  Checks ar[0]  i.e., 2  == 5: The condition is false.

              Step 2:  Checks ar[1]  i.e., 4  == 5: The condition is false.
              Step 3:  Checks ar[2]  i.e., 5  == 5: The condition is true and the loop terminates.
              Though it searches from the first position to the last position and there may be chances that the number to be found
              is present at the last position. It can be cumbersome for large arrays. Thus, it is considered a slow technique.


                Program 8      Write a Java program to input n numbers in an array and search for a given number using
                               Linear Search. Display whether the number is present in the array or not.

                 1       import java.util.*;
                 2       class linear_search
                 3       {

                 4           public static void main(String args[])

                 5           {
                 6               Scanner sc=new Scanner(System.in);
                 7               int size;

                 8               System.out.println("Enter size of array: ");
                 9               size=sc.nextInt();

                10               int ar[ ] = new int[size];
                11               int ns, i, pos=-1;

                12               for (i=0; i<size; i++)
                13               {

                14                     System.out.print("Enter a number: ");

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

                16               }
                17               System.out.print("Enter a number to search: ");

                18               ns=sc.nextInt();
                19               for(i=0; i<size; i++)

                20               {
                21                     if(ar[i]==ns)

                22                   {
                23                          pos=i;

                24                          break;
                25                   }

                26               }
                27               if(pos!=-1)




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