Linear search in Java

Created with Sketch.

 

Linear search in Java

Java program for linear search: Linear search is straightforward; to check if an element is present in the given list, we compare it with every element in the list. If it’s present, then we print the location at which it occurs; otherwise, the list doesn’t contain the element.

Linear search Java program

import java.util.Scanner;

class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];

Scanner in = new Scanner(System.in);
System.out.println(“Enter number of elements”);
n = in.nextInt();
array = new int[n];

System.out.println(“Enter “ + n + ” integers”);

for (c = 0; c < n; c++)
array[c] = in.nextInt();

System.out.println(“Enter value to find”);
search = in.nextInt();

for (c = 0; c < n; c++)
{
if (array[c] == search)     /* Searching element is present */
{
System.out.println(search + ” is present at location “ + (c + 1) + “.”);
break;
}
}
if (c == n)  /* Element to search isn’t present */
System.out.println(search + ” isn’t present in array.”);
}
}

Output of program:
Linear Search Java program output

 

The program finds the first instance of an element to search. You can modify it for multiple occurrences of the same element and count how many times it occurs in the list. Similarly, you can find if an alphabet is present in a string.

Leave a Reply

Your email address will not be published. Required fields are marked *