#include <bits/stdc++.h> // Standard headers (iostream, stack, etc.)
using namespace std; // Standard namespace
// Function to take user input for stack elements
void inputStack(stack<int> &st) { // Pass by reference to modify original stack
cout << "Enter the size : ";
cin >> size; // Get stack size
cout << "Enter stack elements : ";
for(int i=0; i<size; i++) { // Loop to read elements
cin >> temp; // Read element
st.push(temp); // Push onto stack
// Function to print stack elements (consumes a copy of the stack)
void printStack(stack<int> st) { // Pass by value to print a copy
while(!st.empty()) { // Iterate while stack is not empty
cout << st.top() << " "; // Print top element
st.pop(); // Remove top element
// Helper function: Inserts an element into a sorted stack while maintaining sort order
// Assumes stack below 'top' (if any) is already sorted
void insertSorted(stack<int> &st, int data) { // Pass by reference
// Base Case: If stack is empty OR data is greater than/equal to current top
// (This implies data should be pushed here or at the very bottom)
if(st.empty() || st.top() <= data) {
st.push(data); // Place data
return; // Stop recursion
int top = st.top(); // Store current top
st.pop(); // Remove current top
insertSorted(st, data); // Recursively find correct position for 'data'
st.push(top); // Push back stored top (backtracking)
// Main function to sort the entire stack recursively
void sortStack(stack<int> &st) { // Pass by reference
if(st.empty()) { // Base Case: Empty stack is sorted
int top = st.top(); // Store current top element
st.pop(); // Remove current top
sortStack(st); // Recursively sort the remaining stack
insertSorted(st, top); // Insert the stored top element into the now-sorted stack
stack<int> st; // Create a stack
inputStack(st); // Populate stack from user
cout << "Before Sorting : ";
printStack(st); // Print original stack
sortStack(st); // Call function to sort the stack
cout << "After Sorting : ";
printStack(st); // Print sorted stack