Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




LINEAR SEARCH CODE



public class LinearSearch {

    int search(int arr[], int n) {
        
        int len = arr.length;
        for(int i = 0; i < len; i++) {
            
            if(arr[i] == n)
                return i;
        }
        return -1;
    }

    public static void main(String[] args) {

        int arr[] = {5, 3, 6, 2, 1, 4};

        int n = 2;// Element to be searched.

        System.out.print("The Array elements are : ");

        for (int i=0; i<arr.length; i++)
            System.out.print(arr[i] + " ");

        System.out.println("\nElement to be searched : "+n);

        LinearSearch linearSearch = new LinearSearch();

        int index = linearSearch.search(arr, n);

        if(index == -1)
            System.out.print("Element is not present in the array");
        else
            System.out.print("The element "+n+" is present at index " +index);
    }
}



The above code is quite simple,


We will be searching the element '2',


int n = 2;// Element to be searched.

From the array,


int arr[] = {5, 3, 6, 2, 1, 4};

Next, we pass the array and the element '2', to the 'search(...)' method.


int index = linearSearch.search(arr, n);

Explanation of the 'int search(int arr[], int n)' method :



int search(int arr[], int n) {
        
    int len = arr.length;
    for(int i = 0; i < len; i++) {
            
        if(arr[i] == n)
        return i;
    }
    return -1;
}



We need to search the element '2' from the below array.


java_Collections

So, we run a 'for' loop. Starting from the 1st location to the end of the array.


for(int i = 0; i < len; i++) {
            
    if(arr[i] == n)
        return i;
}

And at every step, we keep on checking if the element is present in the array or not.


if(arr[i] == n)
    return i;

If we find the element, we return that particular location.


return i;

java_Collections

But, what if we are searching for an element that is not present in the array?


Say, we are searching for number 8. Which is not present in the array.


In that case, we return '-1'.


return -1;

Which states the number is not found.


Finally, the returned value is stored in the 'index' variable.


int index = linearSearch.search(arr, n);

And we print it using :


System.out.print("The element "+n+" is present at index " +index);	

Output :



 The Array elements are : 5 3 6 2 1 4
 Element to be searched : 2
 The element 2 is present at index 3