R Markdown Activity
Problem: Problem Statement
Find the maximum element in a finite sequence of integers.
Pseudocode
Algorithm FindMax(L)
replace the blanks with the words and numbers and letters used in
the lecture video.
## Input: A list L of n integers
## Output: The maximum element in the list
## max = L[1]
## for i = 2 to length(L) do
## if L[i] > max then
## max = L[i]
## return max
Explanation of Pseudocode
Finish the bullet points below.
1. Initialize max with the first element of the list: Assume the
first element is the largest for now.
2. Loop through the rest of the elements in the list: Start from the
second element and go to the end.
3. Compare each element with max: If the current element is greater
than max, update max.
4. Return max: After the loop ends, the maximum element is the
result.
Example Execution
Finish the bullet points below.
Let’s go through the list using our Pseudocode𝐿={7,−3,0,4,10,2}
step-by-step:
1. Initialize max with the first element: max = 5
2. Compare -3 with max: -3 < 7 (no change)
3. Compare 0 with max: 0 < 7 (no change)
4. Compare 4 with max: 4 < 7 (no change)
5. Compare 10 with max: 10 > 7 (update max = 10)
6. Compare 2 with max: 2 < 10 (no change)
The final value of max is 10.
# Initialize the list
L <- c(7, -3, 0, 4, 10, 2)
# Initialize max with the first element
max <- L[1] # max is now 5
# Loop through the rest of the elements in the list
for (i in 2:length(L)) {
# 'i' will take values 2, 3, 4, 5, 6 sequentially
if (L[i] > max) {
# Compare the current element L[i] with max
max <- L[i] # Update max if L[i] is greater
}
}
# Return the maximum element
max
## [1] 10
Convert to HTML