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. initaialize the first element in the array with the max and
return it
2. loop through the array starting with the second element(2) and
continue
##till you have looped though all the elements in the array
3. compare the max element with the rest of the elements. if the
current element is greater then the next element then update the max
element
4. after the loop has terminates return the max which would be the
largest
##element in the array
Example Execution
Finish the bullet points below.
Let’s go through the list using our Pseudocode𝐿={5,−1,2,8,3,1}
step-by-step:
1. Initialize max with the first element: max = 5
2. Compare -1 with max: -1 < 5 (no change)
3. Compare 2 with max: 2 < 5 (no change)
4. Compare 8 with max: 8 > 5 (update max)
5. Compare 3 with max: 3 < 8 (no change)
6. Compare 1 with max: 1 < 8 (no chagne)
the max == 8
# Initialize the list
L <- c(5, -1, 2, 8, 3, 1)
# Initialize max with the first element
max <- L[1] # we have instantiated that the first element is the max
# Loop through the rest of the elements in the list
for (i in 2:length(L)) {
# note that "i" is the index of the entry of the place value of domain.
# '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] 8
Convert to HTML