Sorting array using Stacks Last Updated : 12 Aug, 2022 Summarize Comments Improve Suggest changes Share Like Article Like Report 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: C++ // C++ program to sort an array using stack #include <bits/stdc++.h> using namespace std; // This function return the sorted stack stack<int> sortStack(stack<int> input) { stack<int> tmpStack; while (!input.empty()) { // pop out the first element int tmp = input.top(); input.pop(); // while temporary stack is not empty // and top of stack is smaller than temp while (!tmpStack.empty() && tmpStack.top() < tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack.top()); tmpStack.pop(); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } void sortArrayUsingStacks(int arr[], int n) { // Push array elements to stack stack<int> input; for (int i=0; i<n; i++) input.push(arr[i]); // Sort the temporary stack stack<int> tmpStack = sortStack(input); // Put stack elements in arrp[] for (int i=0; i<n; i++) { arr[i] = tmpStack.top(); tmpStack.pop(); } } // main function int main() { int arr[] = {10, 5, 15, 45}; int n = sizeof(arr)/sizeof(arr[0]); sortArrayUsingStacks(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; } Java // Java program to sort an // array using stack import java.io.*; import java.util.*; class GFG { // This function return // the sorted stack static Stack<Integer> sortStack(Stack<Integer> input) { Stack<Integer> tmpStack = new Stack<Integer>(); while (!input.empty()) { // pop out the // first element int tmp = input.peek(); input.pop(); // while temporary stack is // not empty and top of stack // is smaller than temp while (!tmpStack.empty() && tmpStack.peek() < tmp) { // pop from temporary // stack and push it // to the input stack input.push(tmpStack.peek()); tmpStack.pop(); } // push temp in // temporary of stack tmpStack.push(tmp); } return tmpStack; } static void sortArrayUsingStacks(int []arr, int n) { // push array elements // to stack Stack<Integer> input = new Stack<Integer>(); for (int i = 0; i < n; i++) input.push(arr[i]); // Sort the temporary stack Stack<Integer> tmpStack = sortStack(input); // Put stack elements // in arrp[] for (int i = 0; i < n; i++) { arr[i] = tmpStack.peek(); tmpStack.pop(); } } // Driver Code public static void main(String args[]) { int []arr = {10, 5, 15, 45}; int n = arr.length; sortArrayUsingStacks(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } } // This code is contributed by // Manish Shaw(manishshaw1) Python3 # Python3 program to sort an array using stack # This function return the sorted stack def sortStack(input): tmpStack = [] while (len(input) > 0): # pop out the first element tmp = input[-1] input.pop() # while temporary stack is not empty # and top of stack is smaller than temp while (len(tmpStack) > 0 and tmpStack[-1] < tmp): # pop from temporary stack and # append it to the input stack input.append(tmpStack[-1]) tmpStack.pop() # append temp in temporary of stack tmpStack.append(tmp) return tmpStack def sortArrayUsingStacks(arr, n): # append array elements to stack input = [] i = 0 while ( i < n ): input.append(arr[i]) i = i + 1 # Sort the temporary stack tmpStack = sortStack(input) i = 0 # Put stack elements in arrp[] while (i < n): arr[i] = tmpStack[-1] tmpStack.pop() i = i + 1 return arr # Driver code arr = [10, 5, 15, 45] n = len(arr) arr = sortArrayUsingStacks(arr, n) i = 0 while (i < n): print(arr[i] ,end= " ") i = i + 1 # This code is contributed by Arnab Kundu C# // C# program to sort an // array using stack using System; using System.Collections.Generic; class GFG { // This function return // the sorted stack static Stack<int> sortStack(Stack<int> input) { Stack<int> tmpStack = new Stack<int>(); while (input.Count != 0) { // pop out the // first element int tmp = input.Peek(); input.Pop(); // while temporary stack is // not empty and top of stack // is smaller than temp while (tmpStack.Count != 0 && tmpStack.Peek() < tmp) { // pop from temporary // stack and push it // to the input stack input.Push(tmpStack.Peek()); tmpStack.Pop(); } // push temp in // temporary of stack tmpStack.Push(tmp); } return tmpStack; } static void sortArrayUsingStacks(int []arr, int n) { // Push array elements // to stack Stack<int> input = new Stack<int>(); for (int i = 0; i<n; i++) input.Push(arr[i]); // Sort the temporary stack Stack<int> tmpStack = sortStack(input); // Put stack elements in arrp[] for (int i = 0; i < n; i++) { arr[i] = tmpStack.Peek(); tmpStack.Pop(); } } // Driver Code static void Main() { int []arr = new int[] {10, 5, 15, 45}; int n = arr.Length; sortArrayUsingStacks(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } } // This code is contributed by // Manish Shaw(manishshaw1) JavaScript <script> // Javascript program to sort an array using stack // This function return the sorted stack function sortStack(input) { var tmpStack = []; while (input.length!=0) { // pop out the first element var tmp = input[input.length-1]; input.pop(); // while temporary stack is not empty // and top of stack is smaller than temp while (tmpStack.length!=0 && tmpStack[tmpStack.length-1] < tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack[tmpStack.length-1]); tmpStack.pop(); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } function sortArrayUsingStacks(arr, n) { // Push array elements to stack var input = []; for (var i=0; i<n; i++) input.push(arr[i]); // Sort the temporary stack var tmpStack = sortStack(input); // Put stack elements in arrp[] for (var i=0; i<n; i++) { arr[i] = tmpStack[tmpStack.length-1]; tmpStack.pop(); } } // main function var arr = [10, 5, 15, 45]; var n = arr.length; sortArrayUsingStacks(arr, n); for (var i=0; i<n; i++) document.write( arr[i] + " "); </script> Output5 10 15 45 Complexity Analysis: Time Complexity: O(n*n).Auxiliary Space: O(n) since auxiliary array is being used to create stack. Comment More infoAdvertise with us Next Article Sorting array using Stacks P PushpamPatel Follow Improve Article Tags : Stack Advanced Data Structure DSA Practice Tags : Advanced Data StructureStack Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Like