106k views
2 votes
An algorithm will be used to identify the maximum value in a list of one or more integers. Consider the two versions of the algorithm below. Algorithm I: Set the value of a variable max to - 1. Iterate through the list of integer values. If a data value is greater than the value of the variable max, set max to the data value. Algorithm II : Set the value of a variable max to the first data value. Iterate through the remaining values in the list of integers. If a data value is greater than the value of the variable max, set max to the data value. Which of the following statements best describes the behavior of the two algorithms? A Both algorithms work correctly on all input values. В Algorithm I always works correctly, but Algorithm II only works correctly when the maximum value is not the first value in the list. Algorithm Il always works correctly, but Algorithm I only works correctly when the maximum value is greater than or equal to - 1. D Neither algorithm will correctly identify the maximum value when the input contains both positive and negative input values.

User ScottyC
by
7.4k points

1 Answer

6 votes

Answer: Choice C

Algorithm Il always works correctly, but Algorithm I only works correctly when the maximum value is greater than or equal to - 1

=====================================================

Step-by-step explanation:

Let's say we have the data set {-4,-3,-2}. The value -2 is the largest.

If we follow algorithm 1, then the max will erroneously be -1 after all is said and done. This is because the max is set to -1 at the start even if -1 isn't in the data set. Then we see if each data value is larger than -1.

  • -4 > -1 is false
  • -3 > -1 is false
  • -2 > -1 is false

Each statement being false means we do not update the max to its proper value -2. It stays at -1.

This is why we shouldn't set the max to some random value at the start.

It's better to use the some value in the data set to initialize the max. Algorithm 2 is the better algorithm. Algorithm 1 only works if the max is -1 or larger.

User Alexis King
by
8.3k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.

9.4m questions

12.2m answers

Categories