Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Sort a stack

Medium Acceptance 69.19% Points 30

The task is to sort a stack so that the top of the stack has the greatest element. You need to complete the function sort() which sorts the elements present in the given stack.

Examples
Example 1

Example 1

Input: Stack: 7 5 9 2 4

Output: 9 7 5 4 2

Explanation: The stack is sorted in descending order where 9 is the topmost element, followed by 7, 5, 4, and 2 at the bottom.

Example 2

Example 2

Input: Stack: 13 19 5 8 1

Output: 19 13 8 5 1

Explanation: The stack is sorted such that the greatest element, 19, is at the top, followed by 13, 8, 5, and 1 at the bottom.

Constraints
  • 1<=N<=100
Hints
  • Expected Time Complexity: O(N*N)
  • Expected Auxilliary Space: O(N) recursive.
Topics
Recursion
Companies
Amazon Microsoft Goldman Sachs IBM Intuit Yahoo
Added 27 Dec 2024 69.19% acceptance
Ln 1, Col 1Sign in to save your code
5
7 5 9 2 4
9 7 5 4 2