Linear Search in Java
One of the most basic searching techniques is linear search in Java programming. There are many other advanced searching algorithms, but we should start with linear search to understand about searching. This technique is very easy to learn searching.
What is Linear Search in Java?
A linear search, also known as sequential search. It is a basic searching algorithm used to find a specific element within an array or a list.
Example of Linear Search in Java Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.util.Scanner; public class LinearSearch{ public static int linearSearch(int[] arr, int tg) { for (int i = 0; i < arr.length; i++) { if (arr[i] == tg) { return i; // return element index } } return -1; // if not found return -1 } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of elements : "); int n = scanner.nextInt(); int[] numbers = new int[n]; System.out.println("Input "+ n +" numbers :"); for (int i = 0; i < n; i++) { numbers[i] = scanner.nextInt(); } System.out.print("Input the number to search : "); int tg = scanner.nextInt(); scanner.close(); int index = linearSearch(numbers, tg); if (index != -1) { System.out.println("Element " + tg + " exist at index " + index); } else { System.out.println("Element " + tg + " not exist in the array."); } } } |
Output
C:\CodeRevise\java>javac LinearSearch.java
C:\CodeRevise\java>java LinearSearch
Enter the number of elements : 5
Input 5 numbers :
3
2
5
4
1
Input the number to search : 4
Element 4 exist at index 3
Check out our other Java Programming Examples