logo CodeStepByStep logo

is_sorted

Language/Type: PHP collections Queue Stack

Write a function named is_sorted accepts an array stack of numbers 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 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 array as your only temorary data structure.
  • Your solution should run in O(N) time, where N is the number of elements of the stack.
Function: Write a PHP 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.