Linear Search
Part of: Array
Searching an Array Linear search (also called sequential search) checks each element one at a time until it finds a target value or runs out of elements. It works on any array, sorted or not. Returning the Index The most useful version reports where the target was found, or -1 if it is absent. By convention, -1 signals "not found" because it is never a valid index. Key points: - Initialize the result to -1 before the loop. - Use == to compare primitives (and .equals for objects like Strings). - break exits early once found, saving needless comparisons. A Boolean "Contains" Variation When you only need to know whether a value is present, return a boolean: This enhanced-for version is clean because position does not matter. Comparing Strings Correctly For object arrays, never use == to compare contents. Use .equals: Efficiency Note Linear search makes at most length comparisons. It is simple and always correct, but for large sorted arrays, binary search (a later topic) is far faster. For the AP subset, linear search is the go-to searching algorithm.
Challenge: Find the Index