Last Updated: 9 Oct, 2021

Sort Using Stack

Moderate
Asked in company
Apple

Problem statement

You are given an array ‘arr’ of size ‘N’ consisting of integers. Your task is to sort the array using a stack.

Note:
Do not use any inbuilt function and other methods to sort the array.
For example:
You are given ‘arr’ = [3 ,4, 1, 2 5], this array sorted will be [1, 2, 3, 4, 5]. Hence the answer is [1, 2, 3, 4, 5]
Input Format:
The first line of input contains the integer ‘T’ representing the number of test cases.

The first line of each test case contains one integer ‘N’, representing the size of the array.

The second line of each test case contains ‘N’ space-separated integers representing the element of the array.
Output Format:
For each test case, print the space-separated integers representing the given array in non-decreasing order.

Print a separate line for each test case.
Constraints:
1 <= T <= 10
1 <= N <= 10^3
0 <= arr[i] <= 10^9

Time Limit: 1 sec
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.

Approaches

01 Approach

In this approach, we will add all the elements of the array in a stack. We will also maintain another stack which will always be sorted, then whenever we find a number, we will insert in it the sorted stack at its position by popping out the elements before it and storing them in the original stack.

 

We create a function sortStact(stk), which will sort the stk, using another stack.

 

Algorithm:

  • In the function function sortStack(stk)
    • Initialize another stack sortedStack
    • While the stk is not empty
      • Set temp as top of the stk and pop the stk
      • While sortedStact is not empty and top of  sortedStack is less than temp
        • Insert sortedStack.top in stk and pop the sortedStack
      • Insert temp into sortedStack
    • Return sortedStack

 

  • Initialise an empty stack stk
  • Iterate num through arr
    • Insert num into stk
  • Set sortedStack as stackSort(stk)
  • Set sol as all the elements poped from the sortedStack
  • Finally, return sol