ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (checking whether an array is sorted in non-decreasing order)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (checking whether an array is sorted in non-decreasing order)? (Arrays are indexed from 0.)
Function isSorted(Array arr)
    for (each i from 1 to length(arr) - 1)
        if (arr[i] < arr[i - 1])
            return false
        end if
    end for
    return true
End Function

Print isSorted({1, 2, 2, 3, 4}), isSorted({1, 3, 2})
  1. A. true false
  2. B. false true
  3. C. true true
  4. D. false false

Correct answer: A. true false

{1,2,2,3,4} never decreases (equal adjacent values are fine for non-decreasing), so it returns true. {1,3,2} drops from 3 to 2, violating the check, so it returns false.

More Pseudocode and Code Tracing questions

Exams that ask this topic