Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

linear search || java

 import java.util.*;


public class Main{

    

    public static int search(int arr[],int size,int key)

    {

        int swap;

        for(int i= 0 ; i < size ; i++)

        {

        if (arr[i] == key)

        {

// optimization the element will be moved to first index so next time itll take less time 

            //swap= arr[0];

           // arr[0]= arr[i];

           // arr[i]=swap;

            

            return i;

        }

        }

        return -1;

    } 

    

    

    public static void main(String[] args)

    {

       Scanner sc = new Scanner(System.in);

       System.out.println("Enter the size of the array");

       int size = sc.nextInt();

       int [] arr = new int[size];

       System.out.println("enter the array elements");

       for (int i= 0 ; i < size ; i++)

       arr[i]= sc.nextInt();

       

       System.out.println("Enter the key");

       int key = sc.nextInt();

       int index = search(arr,size,key);

       if(index> 0)

      System.out.println("key is present on :"+index+" index");

      else 

      System.out.println("key is not present in array");

      for(int i = 0 ; i < size; i++)

      System.out.println(arr[i]);

      

    }

}

Post a Comment

0 Comments