Arrays and Iteration
Linear Search
Walk an array once looking for a target value. Return the index of the
first match, or -1 if none. The simplest possible search loop.
Algorithm
Canonical input arr = {4, 7, 1, 9, 3, 8} with target = 9 finishes
after four compares; the matching 1-indexed position is 4.
early exit
Return the index the moment `arr[i]` equals the target. Walking past it would defeat the point.
sentinel return
A no-match walk falls off the loop and returns `-1`.
Basic Implementation
basic.lua
Replay: real traced execution (multi-file project)
local function linear_search(arr, target)
local i = 1
while i <= #arr do
if arr[i] == target then
return i
end
i = i + 1
end
return -1
end
local arr = {4, 7, 1, 9, 3, 8}
local target = 9
local result = linear_search(arr, target)
print(result)
arr ← [4, 7, 1, 9, 3, 8]
12local arr = {4, 7, 1, 9, 3, 8}13local target = 9values this step[4, 7, 1, 9, 3, 8]arrtarget ← 9
12local arr = {4, 7, 1, 9, 3, 8}13local target = 914local result = linear_search(arr, target)values this step9target[4, 7, 1, 9, 3, 8]arrresult ← -1
13local target = 914local result = linear_search(arr, target)15print(result)values this step-1result9targetmatch ← no
3while i <= #arr do4 if arr[i] == target then5 return ivalues this stepnomatch1i4arr[i]9targetmatch ← no
3while i <= #arr do4 if arr[i] == target then5 return ivalues this stepnomatch2i7arr[i]9targetmatch ← no
3while i <= #arr do4 if arr[i] == target then5 return ivalues this stepnomatch3i1arr[i]9targetmatch ← yes
3while i <= #arr do4 if arr[i] == target then5 return ivalues this stepyesmatch4i9arr[i]9targetresult ← 4
4if arr[i] == target then5 return i6endvalues this step4result4istdout ← 4
14local result = linear_search(arr, target)15print(result)values this step4stdout4result
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Lua: explicit
while i <= #arr dowith an earlyreturn ithe momentarr[i] == target. There is no stdlibfindfor arbitrary sequences (onlystring.find), so the loop already documents the iteration shape the lesson is teaching, and anipairsloop would obscure the running index. - Function signature
local function linear_search(arr, target)documents the array contract; the-1sentinel mirrors the language-neutral spec rather than returningnil(which Lua programmers usually reach for, but which would re-route control flow throughif result == nil then ...in the caller). - The replay shows the running index, the element being checked, and
a
matchindicator on each frame. The 1-based index means the match position prints as4instead of3like the 0-indexed language cohorts.