Table of Contents

    Linear Search in Arrays (Java)

    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:

    1. Start from the first element

    2. Compare each element with the search value

    3. Stop when a match is found

    Algorithm:

    1. Take input array and key

    2. Traverse array from index 0

    3. If element == key → element found

    4. 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