Algorithms

Check each element in order until the target is found — O(n), works on unsorted data.

Version 1.2.0 · current Versions: 1.2.0 1.1.0 1.0.0

Implementations

Sign in to open in IDE Sign in with your Zerethon account to create your own copy of this sample.

Files

LinearSearch.java
// Linear Search (Zerethon Official Sample: linear-search 1.2.0).
// The algorithm as shown in Zerethon Tools.
public class LinearSearch {
    // Returns the index of target, or -1. Works on any (unsorted) array.
    static int linearSearch(int[] a, int target) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == target) return i;
        }
        return -1;
    }
}
LinearSearchTest.java
// Checks for linearSearch. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.
public class LinearSearchTest {
    public static void main(String[] args) {
        int[] descending = new int[100];
        for (int i = 0; i < 100; i++) descending[i] = 100 - i;
        Object[][] cases = {
            {new int[] {}, 1, -1},
            {new int[] {4}, 4, 0},
            {new int[] {4}, 5, -1},
            {new int[] {9, 3, 7}, 9, 0},
            {new int[] {9, 3, 7}, 7, 2},
            {new int[] {5, 1, 5, 1}, 1, 1}, // the first match wins
            {descending, 1, 99},
        };
        for (Object[] c : cases) {
            int got = LinearSearch.linearSearch((int[]) c[0], (int) c[1]);
            if (got != (int) c[2]) {
                System.err.println("linearSearch(..., " + c[1] + ") = " + got + ", expected " + c[2]);
                System.exit(1);
            }
        }
        System.out.println("All " + cases.length + " checks passed.");
    }
}
Main.java entry
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {38, 27, 43, 3, 9, 82, 10, 27};
        System.out.println("List: " + Arrays.toString(numbers));
        for (int target : new int[] {43, 27, 38, 5}) {
            int index = LinearSearch.linearSearch(numbers, target);
            String result = index != -1 ? "found at index " + index : "not found";
            System.out.printf("search %2d: %s%n", target, result);
        }
    }
}
README.md
# Linear Search

Zerethon Official Sample `linear-search`, version 1.2.0, Java 25.

- `LinearSearch.java` — the algorithm, as shown in Zerethon Tools
- `Main.java` — entry file: a short demonstration
- `LinearSearchTest.java` — checks; set it as the entry file to run them

Every `.java` file is compiled together before the entry file's class runs.

This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/linear-search-visualizer

Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Linear Search Visualizer.