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 R DSA version keeps the same data and final output as every other DSA book in this wave.
Basic Implementation
basic.R
Replay: real traced execution (multi-file project)
arr <- c(3, 1, 4, 1, 5, 9, 2, 6)
best <- arr[1]
i <- 2
while (i <= length(arr)) {
if (arr[i] > best) {
best <- arr[i]
}
i <- i + 1
}
cat(best, "\n", sep = "")
arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3
1arr <- c(3, 1, 4, 1, 5, 9, 2, 6)2best <- arr[1]values this step[3, 1, 4, 1, 5, 9, 2, 6]arr3bestreplaced ← no
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this stepnoreplaced1i1arr[i]3bestbest ← 4, replaced ← yes
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this step3 → 4bestyesreplaced2i4arr[i]replaced ← no
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this stepnoreplaced3i1arr[i]4bestbest ← 5, replaced ← yes
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this step4 → 5bestyesreplaced4i5arr[i]best ← 9, replaced ← yes
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this step5 → 9bestyesreplaced5i9arr[i]replaced ← no
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this stepnoreplaced6i2arr[i]9bestreplaced ← no
4while (i <= length(arr)) {5 if (arr[i] > best) {6 best <- arr[i]values this stepnoreplaced7i6arr[i]9beststdout ← 9
1arr <- c(3, 1, 4, 1, 5, 9, 2, 6)2best <- arr[1]values this step9stdout9best
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
arr <- c(3, 1, 4, 1, 5, 9, 2, 6)creates a numeric R vector with the pinned values.- R vectors are 1-based, so
best <- arr[1]seeds the running maximum with3. i <- 2starts the scan at the second R slot, because slot1is already stored inbest.- The loop guard is
while (i <= length(arr)), so the last checked R index is8. - Each candidate is read as
arr[i]; the comparisonarr[i] > bestis a scalar numeric comparison for this data. - When a larger value appears,
best <- arr[i]rebinds the scalarbest. - The checked replay keeps
bestat3for value1, updates to4, stays4for the next1, updates to5, then updates to9. - The final two values,
2and6, do not replace9.
Replay steps
seed from arr[1]: best = 3
arr[2] = 1: best stays 3
arr[3] = 4: best becomes 4
arr[4] = 1: best stays 4
arr[5] = 5: best becomes 5
arr[6] = 9: best becomes 9
arr[7] = 2: best stays 9
arr[8] = 6: best stays 9
cat(best, "\n", sep = "")prints only the final scalar and newline, so the output is9.