Java program to implement linear search

Java8Java Programming Java Technologies

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
raja
Published on 25-Apr-2018 11:11:52
Advertisements