How to perform linear search on arrays in java?

Arrays -: Arrays are a set of elements of same type in continuous memory locations.

There are many operations which are performed on arrays such as searching, sorting, adding etc. Here searching any element in an array is defined.

We can search for any element in an array with two ways that are Linear Search and Binary search.

Linear search -: It is performed by checking each and every element by the existing elements of an array .

Binary search -: Binary searched only on sorted arrays.

Java code to perform linear search -:

import java.util.Scanner;
public class linear_search {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.print(“Enter size of array :”);
int n=s.nextInt();
int[] a=new int [n];
System.out.println(“Enter values of array :”);
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int item,pos=0;
System.err.println(“Enter item to be searched : “);
item=s.nextInt();
for(int j=0;j<a.length;j++)
{
if(a[j]==item)
{
pos=j;
System.out.printf(“Item found at position %s\n”,pos);
return;
}
}
System.out.printf(“Item not found !!!!!\n”);
}
}

Output -:

Leave a Reply