Linear Search Algorithm Java | Beginners Algorithm

In Linear Search Algorithm, we search an element from an array, from one end to another end until we get the required element. It is also called as sequential algorithm.

Time Complexity – O(n)

Space Complextiy – 1

Algorithm with Seperate Method for Linear Search

public class Main {
    public static void main(String[] args) {
        int arr[]={3,2,1,4,5};
        int ele=5;
        System.out.println(linearSearch(arr,ele));
    }
    public static boolean linearSearch(int[] arr,int ele){
        int n=arr.length;
        for(int i=0;i<n;i++){
            if(arr[i]==ele){
                return true;
            }
        }
        return false;
    }
}

Algorithm inside Main Method

public class Main {
    public static void main(String[] args) {
        int arr[]={3,2,1,4,5};
        int n=arr.length;
        int ele=5;
        boolean bool=false;
        for(int i=0;i<n;i++){
            if(arr[i]==ele){
                bool=true;
            }
        }
        System.out.println(bool);
    }
}

Leave a Reply

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

WhatsApp Icon Join For Job Alerts