Sort Integer Stack in Ascending Order

By | September 30, 2023

Given an Integer Stack in Java, sort the stack in increasing order (Ascending Order)

Examples:

Input : Stack: [10, 2, 16, 5, 9, 1] Peek: 1
Output : Stack: [1, 2, 5, 9, 10, 16] Peek: 16

Recommended: Design and Implement Special Stack Data Structure

Approach:
The idea is, pop every element from the original stack and compares it with the temporary stack.
If the popped element from the original stack is less than peek element of the temporary stack, then push the temp stack element to the original stack, call this recursively, until temp is not empty and then push the element at the right place.
Else push the element to the temp stack if the original stack element popped is greater than the temp stack.

Implementation in Java:

// Java Program to sort an Integer Stack
import java.util.Stack;

public class SortStack {
    // Method which returns a sorted stack
    static Stack<Integer> sortStack(Stack<Integer> stack) {
        // Create another temporary stack
        Stack<Integer> tempStack = new Stack<Integer>();
        // Iterate until the original stack is empty
        while (!stack.isEmpty()) {
            // Popped element from the original stack
            int s = stack.pop();

            // Check for the specified condition
            while (!tempStack.isEmpty() && (tempStack.peek() > s))
                stack.push(tempStack.pop());

            // Pushed in the temp stack
            tempStack.push(s);
        }

        // Return the stack
        return tempStack;
    }

    // Driver Code
    public static void main(String[] args) {
        // Declare the Stack and Initialize the elements in it
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(10);
        stack.push(2);
        stack.push(16);
        stack.push(5);
        stack.push(9);
        stack.push(1);

        // Print before sorting
        System.out.println(stack + " Peek: " + stack.peek());

        // Sort the stack
        stack = sortStack(stack);

        // Print after sorting
        System.out.println(stack + " Peek: " + stack.peek());
    }
}

Output:

[10, 2, 16, 5, 9, 1] Peek: 1
[1, 2, 5, 9, 10, 16] Peek: 16

Time Complexity: O(n^2) 
Space Complexity: O(n)

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.