Linear Search in Arrays (Java)
☰Fullscreen
Table of Content:
What is Linear Search?
Linear search is the simplest searching technique.
It checks each element one by one until the required element is found or the array ends.
How Linear Search Works:
-
Start from the first element
-
Compare each element with the search value
-
Stop when a match is found
Algorithm:
-
Take input array and key
-
Traverse array from index 0
-
If element == key → element found
-
If end reached → element not found
Java Program:
class LinearSearch { public static void main(String[] args) { int[] arr = {10, 25, 30, 45, 50}; int key = 30; boolean found = false; for (int i = 0; i < arr.length; i++) { if (arr[i] == key) { System.out.println("Element found at index " + i); found = true; break; } } if (!found) { System.out.println("Element not found"); } } }
Time Complexity:
-
Best Case: O(1)
-
Worst Case: O(n)
Advantages:
-
Simple to understand
-
Works on unsorted arrays
Disadvantages:
-
Slow for large datasets