Linear Search in Java Program

Linear Search is one of most simplest searching technique but it is not used widely because it is slower than Binary Search and Hashing.
Algorithm:
  1. Traverse the array
  2. Match the key element with array element
  3. If key element is found, return the index position of the array element
  4. If key element is not found, return -1
Java Program - Linear Search


public class LinearSearchExample{

    public static int LinearSearch(int arr[],int key){
        
        int i,n=arr.length;
        
        for(i=0;i<n;i++){
            if(arr[i]==key){
                return i;
            }
        }
        
        return -1;
        
    }
    
    public static void main(String []args){
       
        int arr[] = {10,14,19,26,27,31,33,35,42,44}; 
        
        int key=31;
        
        int index = LinearSearch(arr,key);
        
        if(index==-1){
            System.out.println(key+" was not found");
        }else{
            System.out.println(key+" was found at "+index+" index");
        }
        
    }
}


Comments