Linear Search is a used for finding the key element in the multiple of elements in a given array. Now a days, Linear search is not that much used because Linear search algorithm is slow as compare to binary search or hashing.

Algorithm:

  • First step is traverse the array
  • Next is match the search element with the array elements.
  • If the search element is found then return the index position of the array element.
  • If not found then return -1

Programs:

public class LinearSearch{    
public static int linearSearch(int[] a, int key){    
        for(int i=0;i<a.length;i++){    
            if(a[i] == key){    
                return i;    
            }    
        }    
        return -1;    
    }    
    public static void main(String a[]){    
        int[] a1= {10,20,30,50,70,90};    
        int key = 50;    
        System.out.println(key+" is found at index position: "+linearSearch(a1, key));    
    }    
}    

Output:

70 is found at index position 4
import java.util.Scanner;  
   
class LinearSearch   
{  
  public static void main(String args[])  
  {  
    int c, num, search, array[];  
   
    Scanner in = new Scanner(System.in);  
    System.out.println("Enter number of elements");  
    num = in.nextInt();   
    array = new int[num];  
   
    System.out.println("Enter " + num + " elements");  
   
    for (int i = 0; i < num; i++)  
      array[i] = in.nextInt();  
   
    System.out.println("Enter the value to find");  
    search = in.nextInt();  
   
    for (int i = 0; i < n; i++)  
    {  
      if (array[i] == search)    
      {  
         System.out.println(search + " is present at location " + (i + 1) + ".");  
          break;  
      }  
   }  
   if (i == num)   
      System.out.println(search + " isn't present in array.");  
  }  
}  

Output:

Linear Search

If you want to learn about the binary search then click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top