Linear Search In Java

Sharing is healthy !!

Hey!! Guys, how are you doing….. today you will learn linear search in java. Let us see what linear search in java means??

what is linear search?

Basically linear search in java is simple and executed to check if an element exists in the given array. Then search element is compared with every element in an array. The search continues until the element is found else the array does not contain the element.

example: Linear Search In Java

Also Read – Binary Search Program Java

import java.util.Scanner;

public class Linear_Search_In_Java {

public static void main(String[] args) {

int a;
int b;
int search;
int array[];

Scanner sc = new Scanner(System.in);
System.out.println("Please enter number of elements: ");
b = sc.nextInt();
array = new int[b];

System.out.println("Please enter " + b + " integers:");

for(a = 0;a < b;a++)
array[a] = sc.nextInt();

System.out.println("Please enter value to find: ");
search = sc.nextInt();

for(a = 0;a < b;a++)
{
if(array[a] == search)
{
System.out.println(search + " is present at " + (a + 1) + " location.");
break;
}
}
if(a == b)
System.out.println(search + " is not present in an array.");
}
}

Output:

Linear Search In Java

Sharing is healthy !!

Leave a Reply

Your email address will not be published.