Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.

Algorithm

Basic Implementation

basic.sh
#!/usr/bin/env bash
set -euo pipefail
arr=(3 1 4 1 5 9 2 6)
best=${arr[0]}
for ((i = 1; i < ${#arr[@]}; i++)); do
	if [ "${arr[i]}" -gt "$best" ]; then
		best=${arr[i]}
	fi
done
echo "$best"

Complexity

  • Time: O(n)
  • Space: O(1)

Implementation notes

  • set -euo pipefail is present at the top of the script, so this lesson runs with the same strict shell settings as the rest of the Bash examples.
  • arr=(3 1 4 1 5 9 2 6) is a Bash indexed array. The indexes used here are zero-based.
  • best=${arr[0]} seeds the running maximum with 3.
  • for ((i = 1; i < ${#arr[@]}; i++)); do is Bash arithmetic-loop syntax. ${#arr[@]} is 8, so the loop scans indexes 1 through 7.
  • if [ "${arr[i]}" -gt "$best" ]; then uses the numeric comparison operator -gt. The values are quoted while Bash compares them as numbers.
  • best=${arr[i]} replaces the running maximum only when the current value is larger.

Replay steps

seed: best = 3 from arr[0]
i=1 value 1: keep 3
i=2 value 4: replace 3 -> 4
i=3 value 1: keep 4
i=4 value 5: replace 4 -> 5
i=5 value 9: replace 5 -> 9
i=6 value 2: keep 9
i=7 value 6: keep 9
  • echo "$best" prints exactly 9.
execution replay The checked-in replay follows the language-neutral state table for `array-find-max`.
cross-language comparison This Bash DSA version keeps the same data and final output as every other DSA book in this wave.