Linear search in java

    Searching is a way of finding an element in an array. This can be done by many ways. Basically, two methods are used.

  • ·       Linear search
  • ·       Binary search

Linear search in java:

              It is a sequential search which finds a data by looking the elements one by one until the data is found.

Steps to follow to write the java program:

  • ·       Import a built in package java.util.Scanner.
  • ·       Create a class with main function.
  • ·       Add the input statements to get the input.
  • ·       First, read the number of elements  for array. Next, get the array elements.
  • ·       Finally, get the data to be searched in the array.
  • ·       Set two variables j and key as 0.
  • ·       Using a loop, repeat the process for all elements in the array.
  • ·       Check the key value with data in the array.
  • ·       If the data is found, print the position and data. Set the key as 1.
  • ·       Finally, check the key value, if it is 0,print the data is not found message.

Program:

import java.util.Scanner;

public class LinearPgm {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0,key=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

        System.out.println("Enter the data to be searched");

        int data = scanner.nextInt();

         for (j = 0; j < a.length; j++) {

            if (a[j] == data) {

              System.out.print("The data is found at"+ (j+1) +"Position");

              key =1;

            }

          }

         if(key==0)

          System.out.println("The data is not found");

  }

 }           

Output:

C:\blog>javac LinearPgm.java

C:\blog>java LinearPgm

Enter the number of elements5

Enter 5 elements:

12

24

35

46

57

Enter the data to be searched

35

The data is found at3Position

Note: Linear search is not efficient for large data.

This is the way of creating linear search program in java.

No comments:

Post a Comment