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 Swift DSA version keeps the same data and final output as every other DSA book in this wave.
Basic Implementation
basic.swift
Replay: real traced execution (multi-file project)
let arr = [3, 1, 4, 1, 5, 9, 2, 6]
var best = arr[0]
for i in 1..<arr.count {
if arr[i] > best {
best = arr[i]
}
}
print(best)
arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3
1let arr = [3, 1, 4, 1, 5, 9, 2, 6]2var best = arr[0]values this step[3, 1, 4, 1, 5, 9, 2, 6]arr3bestreplaced ← no
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this stepnoreplaced1i1arr[i]3bestbest ← 4, replaced ← yes
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this step3 → 4bestyesreplaced2i4arr[i]replaced ← no
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this stepnoreplaced3i1arr[i]4bestbest ← 5, replaced ← yes
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this step4 → 5bestyesreplaced4i5arr[i]best ← 9, replaced ← yes
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this step5 → 9bestyesreplaced5i9arr[i]replaced ← no
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this stepnoreplaced6i2arr[i]9bestreplaced ← no
3for i in 1..<arr.count {4 if arr[i] > best {5 best = arr[i]values this stepnoreplaced7i6arr[i]9beststdout ← 9
7}8print(best)values this step9stdout9best
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Swift infers
arras an[Int]fromlet arr = [3, 1, 4, 1, 5, 9, 2, 6]; theletbinding means the array is not mutated or rebound. var best = arr[0]seeds the running maximum from the first element, so the loop can start at index1without optional or sentinel state.- The scan uses
for i in 1..<arr.count, visiting indexes1through7and reading each candidate witharr[i]. if arr[i] > bestperforms a strictIntcomparison; equal values do not replace the current maximum.- Only
bestmutates during the loop. The trace records replacements ati=2(3 -> 4),i=4(4 -> 5), andi=5(5 -> 9), with later values leavingbestat9. print(best)writes the finalIntas9.