Arrays and Iteration
Find Maximum
Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.
Algorithm
execution replay
The checked-in replay follows the language-neutral state table for `array-find-max`.
cross-language comparison
This Lua DSA version keeps the same data and final output as every other DSA book in this wave.
Basic Implementation
basic.lua
Replay: real traced execution (multi-file project)
arr = {3, 1, 4, 1, 5, 9, 2, 6}
best = arr[1]
for i = 2, #arr do
if arr[i] > best then
best = arr[i]
end
end
print(best)
arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3
1arr = {3, 1, 4, 1, 5, 9, 2, 6}2best = arr[1]values this step[3, 1, 4, 1, 5, 9, 2, 6]arr3bestreplaced ← no
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this stepnoreplaced1i1arr[i]3bestbest ← 4, replaced ← yes
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this step3 → 4bestyesreplaced2i4arr[i]replaced ← no
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this stepnoreplaced3i1arr[i]4bestbest ← 5, replaced ← yes
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this step4 → 5bestyesreplaced4i5arr[i]best ← 9, replaced ← yes
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this step5 → 9bestyesreplaced5i9arr[i]replaced ← no
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this stepnoreplaced6i2arr[i]9bestreplaced ← no
3for i = 2, #arr do4 if arr[i] > best then5 best = arr[i]values this stepnoreplaced7i6arr[i]9beststdout ← 9
7end8print(best)values this step9stdout9best
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
arr = {3, 1, 4, 1, 5, 9, 2, 6}is a Lua table used as an array.- Lua arrays are 1-based here:
best = arr[1]seeds the scan with3. - The loop is
for i = 2, #arr do, so#arrsupplies the upper bound8for this dense table with nonilgaps. - Each pass reads
arr[i]and compares withif arr[i] > best then. - Only larger values assign
best = arr[i]; equal or smaller values leave the currentbestunchanged. - The replay uses language-neutral position labels: its
arr[0]seed is Lua'sarr[1], and its scan positionsi=1throughi=7correspond to Lua loop indexes2through8. - The replay starts with
best = 3, then keeps3for value1, replaces it with4, keeps4for value1, replaces it with5, then replaces it with9. - The final values
2and6do not replace9. print(best)writes the final maximum as9.