Java Linear Search Program

Introduction

Linear Search is one of the simplest searching algorithms in Java. It searches for an element by checking each item in the array one by one until the desired element is found or the end of the array is reached.

Unlike Binary Search, Linear Search does not require the array to be sorted, making it suitable for searching in small or unsorted datasets.

For example:

Array:


15 25 10 40 35

Search Element:


40

Output:

Element found at index 3

Although Linear Search is not the fastest searching algorithm, it is easy to understand and implement. It is commonly taught to beginners because it introduces essential programming concepts such as arrays, loops, conditional statements, and searching techniques.

In this tutorial, you’ll learn how Linear Search works, its algorithm, Java implementation, time complexity, advantages, disadvantages, interview questions, and more.

What is Linear Search?

Linear Search (also called Sequential Search) is a searching algorithm that starts from the first element of an array and compares each element with the target value until a match is found.

If the target element exists, the algorithm returns its position (index). Otherwise, it reports that the element is not found.

Example:

Array:


15 25 10 40 35
Search = 40

Step 1:
15 ≠ 40

Step 2:
25 ≠ 40

Step 3:
10 ≠ 40

Step 4:
40 = 40

Element Found.

When to Use Linear Search?

Linear Search is suitable when:

  • The array is small.
  • The data is unsorted.
  • Simplicity is more important than speed.
  • Frequent insertions and deletions occur.
  • Sorting the data is unnecessary.

Syntax


for (int i = 0; i < array.length; i++) {
    if (array[i] == key) {
        return i;
    }
}
return -1;

Java Linear Search Program


public class LinearSearch {
    public static void main(String[] args) {
        int[] numbers = {15, 25, 10, 40, 35};
        int key = 40;
        boolean found = false;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == key) {
                System.out.println("Element found at index: " + i);
                found = true;
                break;
            }
        }
        if (!found) {
            System.out.println("Element not found.");
        }
    }
}

Output

Element found at index: 3

How Linear Search Works?

Consider the following array:


15 25 10 40 35

Search Element:
40

Step 1
Compare 15 with 40
Not Equal

Step 2
Compare 25 with 40
Not Equal

Step 3
Compare 10 with 40
Not Equal

Step 4
Compare 40 with 40
Equal

Element Found.

Explanation of the Program

Step 1: Declare the Array


int[] numbers = {15, 25, 10, 40, 35};

This array contains the values that will be searched.

Step 2: Store the Search Element


int key = 40;

The variable key stores the element to be searched.

Step 3: Traverse the Array


for(int i = 0; i < numbers.length; i++)

The loop checks every element one by one.

Step 4: Compare Each Element


if(numbers[i] == key)

If the current element matches the search value, display its index.

Step 5: Handle Element Not Found

If the loop finishes without finding the element, display:

Element not found.

Java Linear Search Using a Method


public class LinearSearch {
    static int linearSearch(int[] arr, int key) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] numbers = {12, 45, 67, 23, 89};
        int index = linearSearch(numbers, 67);
        if (index != -1)
            System.out.println("Element found at index: " + index);
        else
            System.out.println("Element not found.");
    }
}

Output


Element found at index: 2

Java Linear Search Using User Input


import java.util.Scanner;
public class LinearSearch {
    public static void main(String[] args) {
        int[] numbers = {5, 15, 25, 35, 45};
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number to search: ");
        int key = scanner.nextInt();
        boolean found = false;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == key) {
                System.out.println("Element found at index: " + i);
                found = true;
                break;
            }
        }
        if (!found)
            System.out.println("Element not found.");
        scanner.close();
    }
}

Output

Enter number to search:
35

Element found at index: 3

Algorithm

  1. Read the array.
  2. Read the element to search.
  3. Start from the first element.
  4. Compare each element with the search key.
  5. If a match is found, display its index.
  6. Otherwise, continue searching.
  7. If the loop ends, display "Element not found."

Flowchart


      Start
        │
    Read Array
        │
Read Search Element
        │
Compare Current Element
        │
   Match Found?
 ┌──────┴──────┐
Yes           No
 │             │
Print Index    Check Next Element
 │             │
 └──────┬──────┘
        │
  Element Found?
        │
      Yes / No
        │
  Print Result
        │
       End

Time Complexity

Case Time Complexity
Best Case O(1)
Average Case O(n)
Worst Case O(n)

In the worst case, the algorithm checks every element before determining whether the target exists.

Space Complexity


O(1)

Linear Search uses only a few extra variables, so it requires constant memory.

Advantages of Linear Search

  • Very easy to understand and implement.
  • Works on both sorted and unsorted arrays.
  • No preprocessing or sorting required.
  • Suitable for small datasets.
  • Uses constant extra memory.

Disadvantages of Linear Search

  • Slow for large datasets.
  • Time complexity is O(n).
  • Requires checking each element one by one.
  • Less efficient than Binary Search for sorted arrays.

Linear Search vs Binary Search

Feature Linear Search Binary Search
Requires Sorted Data No Yes
Best Case O(1) O(1)
Average Case O(n) O(log n)
Worst Case O(n) O(log n)
Suitable for Small Data Yes Yes
Suitable for Large Sorted Data No Yes

Common Mistakes

1. Forgetting to Break the Loop

Incorrect:


if(numbers[i] == key){
    found = true;
}

The loop continues even after finding the element.

Correct:


break;

2. Using Incorrect Loop Condition

Incorrect:


for(int i = 0; i <= numbers.length; i++)

This causes an ArrayIndexOutOfBoundsException.

Correct:


for(int i = 0; i < numbers.length; i++)

3. Forgetting the "Not Found" Case

Always handle the situation when the element does not exist.


if(!found){
    System.out.println("Element not found.");
}

4. Comparing Wrong Variables

Incorrect:


if(numbers[i] == i)

Correct:


if(numbers[i] == key)

5. Forgetting to Close Scanner

Always close the Scanner object after reading input.


scanner.close();

Real-Life Applications

Linear Search is commonly used in:

  • Searching names in a small contact list.
  • Finding a value in an unsorted array.
  • Student record lookup in small applications.
  • Inventory management systems.
  • Basic search functionality in educational projects.
  • Simple games and console applications.

Summary

The Java Linear Search program is one of the most fundamental searching algorithms every beginner should learn. It introduces key programming concepts such as arrays, loops, conditional statements, and sequential searching.

Linear Search is simple to implement and works on both sorted and unsorted data, making it ideal for small datasets and beginner-level applications. However, because it has a time complexity of O(n), it becomes inefficient for large datasets. In those cases, algorithms like Binary Search are preferred when the data is sorted.

Related Java Tutorials