Java program to implement linear search


Linear search is a very simple search algorithm. In this type of search, a sequential search is done for all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.

Algorithm

1.Get the length of the array.
2.Get the element to be searched store it in a variable named value.
3.Compare each element of the array with the variable value.
4.In case of a match print a message saying element found.
5.else, print a message saying element not found

Example

Live Demo

public class LinearSearch {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;
      int value = 63;

      for (int i=0 ;i< size-1; i++){
         if(array[i]==value){
            System.out.println("Element found index is :"+ i);
         }else{
            System.out.println("Element not found");
         }
      }
   }
}

Output

Element found index is :3

Updated on: 13-Mar-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements