Given a stack of integers st[], sort the stack in ascending order, so that…

PYQ IBM Hiring Assessment 2024

Given a stack of integers st[], sort the stack in ascending order, so that after sorting the smallest element sits at the bottom of the stack and the largest element sits at the top.

Input format

The first line contains a single integer n — the number of elements in the stack.
The second line contains n space-separated integers describing the stack from top to bottom: the first integer is the element currently on top and the last integer is the element at the bottom.

Output format

Print the elements of the sorted stack on a single line, separated by single spaces, listed from top to bottom — so the largest element is printed first and the smallest element last.

Examples :

Input:
5
41 3 32 2 11
Output: 41 32 11 3 2
Explanation: read from top to bottom the stack holds 41, 3, 32, 2, 11, so from bottom to top it holds 11, 2, 32, 3, 41. After sorting, the smallest element 2 sits at the bottom and the largest element 41 sits at the top, and listing that sorted stack from top to bottom prints 41 32 11 3 2.

Input:
3
3 2 1
Output: 3 2 1
Explanation: read from top to bottom the stack holds 3, 2, 1, so from bottom to top it holds 1, 2, 3, which is already ascending. No element has to move, so the same listing is printed.

Constraints:
1 ≤ n = st.size() ≤ 103
0 ≤ stack element ≤ 103

Attempted by 10 students.

Sign up free to check your answer

Sign up free

Explore the full course: Coding For Placement

Loading lesson…