Skip to content
Preview · sample content · Explore all pages

Linear search in Java

Last updated: 28 Sept 20264 min read
guide
By AITrove Editorial

Scan an array and return the position of a target.

Implementation

Java
static int find(int[] values, int target) {
    for (int i = 0; i < values.length; i++) {
        if (values[i] == target) return i;
    }
    return -1;
}

Reasoning

In the worst case every element is checked, so time grows linearly with array length. Extra space stays constant. This version assumes a non-null array.

Check

Try a target at the first position, at the last position and a missing target.

Common Mistakes

Check empty inputs and invalid values before applying this operation to application data. State whether a method edits shared state or returns a separate value.

java-dsa
Storage details