Linear Search: What It Is and Why You Should Know It

Linear Search: What It Is and Why You Should Know It

·

2 min read

based on Wekipidia, A linear search, also known as a sequential search, is a technique used in computer science to locate an element inside a list. Up until a match is discovered or the entire list has been searched, each element of the list is successively checked.

Linear Search

  • Best Case

o(1).png

  • Worst Case

o(N).png

  • Space Complexity : O ( 1 )
Function linearSearch(list, Target):
     IF length(lis)==0
            RETUN -1
     ELSE
            FOR index FROM 0 -> length(list)-1:
               IF list[index] == Target THEN
                   RETURN index
               End IF
               End LOOP         
     Return -1
End Function

Implementation using Programming Language

  • We're going to use the Java programming language to build the linear search method.
static boolean LinearSearch(int[] list,int target){
        if(list.length==0){
            return false;
        }
        else{
            for (int i = 0; i <list.length; i++) {
                if(list[i]==target)
                    return true;
            }
        }
      return false;
    }
  • Find max of array
static int max(int[] list){
        //trying to find max of array
        if(list.length==0){
            return -1; 
        }
        int maxElement=list[0];
        for (int element:list) {
            if(element>maxElement)
                maxElement=element;
        }
        return maxElement; // return the max element
    }
  • Searching in 2D Array
static boolean Search2D(int[][] list,int target){
        if(list.length==0){
            return false;
        }
        for (int i = 0; i < list.length ; i++) {
            for (int j = 0; j < list[i].length; j++) {
                if(target==list[i][j])
                    return true;
            }
        }
        return false; // element not founded
    }
  • Search in a certain range
static boolean rangeSearch(int[] list,int start,int end,int target){
        if(list.length==0){
            return false;
        }
        else{
            for (int i = start; i <=end ; i++) {
                if(list[i]==target)
                    return true;
            }

        }
        return false; // element not founded
    }