lesson

Updated 6 days ago
Imagine dropping your student ID card into a completely shuffled pile of 500 loose cards. How would you find it?
Since the pile is unordered, you have no choice: you must flip through the cards one by one from top to bottom until you spot your photo.
How Linear Search Works
A linear search is an algorithm that inspects every element in a list one by one, starting from the first item until it finds a match or reaches the end. An algorithm is a clear, step-by-step set of instructions designed to perform a specific task.
๐Interactive step-by-step visual of a linear search. Display an unsorted array: [12, 45, 7, 23, 9] in rounded card boxes with indices 0 to 4 labeled beneath. Target is 7. An animated pointer/magnifying glass checks index 0 (12 != 7, marked red X), then index 1 (45 != 7, marked red X), then index 2 (7 == 7, marked green checkmark with 'Found!'). Light theme: #f8fafc background, #1e2945 text, #22b7ff accent for active pointer, #10b981 for success, #ef4444 for mismatch. Clean modern UI, fits 350px width.
What makes this approach special is that it works on unsorted data without needing any prior arrangement. But how do we track our exact position through the data step by step?
Tracing a Linear Search
In programming, an array is an ordered list of items where each position is numbered by an index, which starts at index 0. To trace an algorithm means to follow its execution line-by-line, recording how variables change at each step.
Let's trace a search for the target value
22 in the array [9, 14, 22, 5, 3].๐A step-by-step trace card diagram for searching target 22 in array [9, 14, 22, 5, 3]. Show 3 sequential step rows: Step 1 (Index 0, Value 9, Compare '9 == 22?', Result 'False, continue'), Step 2 (Index 1, Value 14, Compare '14 == 22?', Result 'False, continue'), Step 3 (Index 2, Value 22, Compare '22 == 22?', Result 'True -> Return index 2'). Light modern card styling, white boxes, clear borders, green badge for match.
Searching for an item that exists is straightforward. But what happens if the item is not in the array at all?
Unsuccessful Searches
When a target is missing, the algorithm must check all n items in the list. Once it reaches past the final index without finding a match, it signals that the item is missing by returning -1.