Learnitweb

Linear Search In Java

1. Introduction

Linear Search, also known as sequential search, is a simple search algorithm that checks every element in a list sequentially until the target value is found or the end of the list is reached.

It is best used when:

  • The list is unsorted.
  • The dataset is small or rarely searched.

2. Characteristics of Linear Search

  • Time Complexity:
    • Best case: O(1) (element is at the first position)
    • Worst case: O(n) (element not present or at the last position)
    • Average case: O(n)
  • Space Complexity: O(1) – constant space
  • Does not require sorting
    • Works on both arrays and lists

3. Linear Search Algorithm Steps

  • Start from the first element.
  • Compare the target element with the current element.
  • If they match, return the current index.
  • If not, move to the next element.
  • Repeat until the end of the array.
  • If no match is found, return -1.

4. Java Code Example

public class LinearSearchExample {

    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;  // Found, return index
            }
        }
        return -1;  // Not found
    }

    public static void main(String[] args) {
        int[] numbers = {15, 22, 9, 31, 56, 48};
        int target = 31;

        int result = linearSearch(numbers, target);

        if (result != -1) {
            System.out.println("Element found at index: " + result);
        } else {
            System.out.println("Element not found in the array.");
        }
    }
}

5. Text-Based Visual Representation

Let’s say:

arr = [4, 8, 15, 23, 42]
target = 15

Step-by-step:

Step 1: arr[0] = 4     → not match
Step 2: arr[1] = 8     → not match
Step 3: arr[2] = 15    → match found

6. When Linear Search is Not Ideal

  • Large datasets → becomes slow (O(n))
  • Sorted arrays → binary search is more efficient (O(log n))

7. When to Use Linear Search

Use Linear Search when:

  • The data is unsorted
  • You expect the target near the beginning
  • The dataset is small
  • You need a quick, simple search method