VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorting-array-using-stacks/

⇱ Sorting array using Stacks - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorting array using Stacks

Last Updated : 11 Jul, 2025

Given an array of elements, the task is to sort these elements using a stack.

Prerequisites: Stacks

Examples:  

Input : 8 5 7 1 9 12 10
Output : 1 5 7 8 9 10 12 
Explanation :
Output is sorted element set

Input : 7 4 10 20 2 5 9 1
Output : 1 2 4 5 7 9 10 20 

We basically use Sort a stack using a temporary stack. Then we put sorted stack elements back to the array.  

Implementation:


Output
5 10 15 45 

Complexity Analysis:

  • Time Complexity: O(n*n).
  • Auxiliary Space: O(n) since auxiliary array is being used to create stack.
Comment
Article Tags: