Computer Science, asked by pallabiB, 3 months ago

Write a program to perform linear search on a list of integers given below, to search

for an element input by the user, if it is found display the element along with its

position, otherwise display the message ―Search element not found‖.

5, 7, 9, 11, 15, 20, 30, 45, 89,97 .with variable description ​

Answers

Answered by Oreki
6

Program

import java.util.Scanner;

public class LinearSearching {

   static int linearSearch(int[ ] array, int search) {

       for (int i = 0; i < array.length; i++)

           if (array[i] == search)

               return i;

       return -1;

   }

   public static void main(String[ ] args) {

       Scanner sc = new Scanner(System.in);

       // Accepting elements into the Array.

       System.out.println("Enter the Array elements - ");

       int[ ] array = new int[10];

       for (int i = 0; i < 10; )

           array[i++] = sc.nextInt( );

       // Accepting the search element.

       System.out.print("Enter element to be searched - ");

      int searchElement = sc.nextInt( );

       // Getting the element position.

       int position = linearSearch(array, searchElement);

       System.out.print(position != -1 ? "Is present at index position " + position :  "Not present");

   }

}

Algorithm

  • Accepting the elements into the array using Scanner class.
  • Accepting the element to be searched for.
  • Searching the element using the Linear Search technique.
  • The method/function for the specified task returns -1 if element not present else the position of the element in the array.
  • Printing the message accordingly for the result obtained by the method.
Attachments:
Similar questions