logo CodeStepByStep logo

isSorted

Language/Type: C++ stack queue collections STL
Related Links:

Write a function named isSorted accepts a reference to a stack of integers as a parameter and returns true if the elements in the stack occur in ascending (non-decreasing) order from top to bottom, else false. That is, the smallest element should be on top, growing larger toward the bottom. An empty or one-element stack is considered to be sorted. For example, if passed the following stack, your function should return true:

bottom {20, 20, 17, 11, 8, 8, 3, 2} top

The following stack is not sorted (the 15 is out of place), so passing it to your function should return a result of false:

bottom {18, 12, 15, 6, 1} top

When your function returns, the stack should be in the same state as when it was passed in. In other words, if your function modifies the stack, you must restore it before returning.

Constraints: You may use one queue or one stack (but not both) as auxiliary storage. Do not declare any other auxiliary data structures (e.g. arrays, Grids, vectors, etc.), but you can have as many simple variables as you like. Your solution should run in O(N) time, where N is the number of elements of the stack.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.