Tuesday, February 4, 2020

Linear Search in Java

Linear Search

A sequential search is a simple searching technique, which has linear time complexity. We start matching the elements one by one sequentially, if the match is found then, it will return the position of the match, otherwise, some default value that is set for not found will be returned. The complexity of the sequential search is O(n).


Example
import java.util.Scanner;

public class LinearSearch {
    public static void main(String[] arg) {
    LinearSearch ls=new LinearSearch();// Linear/Sequential Search
    int arr[]= {18,72,55,112,73,45,39,40,27,631,1,-45,68};
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter the number to search in 18,72,55,112,73,45,39,40,27,631,1,-45,68");
    int num=scan.nextInt();
    //LinearSearch ls=new LinearSearch();
    int result=ls.seq_ser(num, arr);
    if(result==-1)
    {
        System.out.println("Not Found");
    }
    else
    {
        System.out.println("Found at postion "+result);
    }
    }
    public int seq_ser(int ser,int arr[])
    {
        int pos=-1;//will return -1 if not found
        for(int i=0;i<arr.length;i++)
        {
            if(arr[i]==ser)
            {
                pos=i;
                break;
            }
        }
        return pos;
    }
}

Video Tutorial