Linear Search in Arrays (Java)

Rumman Ansari   Software Engineer   2025-12-27 05:20:17   78  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰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:

  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


MCQ Available

There are 1 MCQs available for this topic.

1 MCQ


Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.