Linear Search: Check One by One

The simplest search

Start at the first item and check each one until you find what you want or run out of items. It works on any array, sorted or not.

public class Main {
    static int indexOf(String[] items, String wanted) {
        for (int i = 0; i < items.length; i++) {
            if (items[i].equals(wanted)) return i;   // found: stop early
        }
        return -1;                                   // -1 means "not here"
    }

    public static void main(String[] args) {
        String[] bag = {"pen", "phone", "keys", "wallet", "charger"};
        System.out.println(indexOf(bag, "keys"));
        System.out.println(indexOf(bag, "umbrella"));
    }
}

Output

2
-1
CaseChecks for n items
best (first item)1
worst (last item, or missing)n
Big-OO(n)

Think of it like this: Looking for your keys by emptying your bag item by item. Fine for a small bag – terrible for a warehouse.

Remember: Returning -1 for “not found” is a Java habit: String.indexOf and ArrayList.indexOf do the same.

HOME LABS COMMUNITY DASHBOARD