Sort Elements of a Stack in Descending Order in Java



In this article, we will learn to sort the elements of the stack in descending order. A stack is a data structure that works on the LIFO (Last In First Out) principle which means that the last added item is removed first. One real-life example of a stack is browser history where the last used website appears first. In this article, we are going to discuss, how we can sort the element of stack in descending order in Java

Problem Statement

In the given problem, we have a stack of unsorted integer elements, which we have to sort in descending order, meaning the largest element is on top and the smallest is at the bottom.

Input

Original Stack: [4, 2, 9, 7]

Output

Original Stack: [4, 2, 9, 7]
Sorted Stack in Descending order: [9, 7, 4, 2]

Java program to sort the elements using a recursive approach 

We will use recursion to sort the stack. Below are the steps we follow to sort the stack in descending order:

  • Import the Stack class from java.util to use the stack data structure.
  • The sortStack method will remove each element from the stack recursively until it's empty, storing the removed elements temporarily.
  • In sortStack, use stack.pop() to remove the top element and call sortStack again until all elements are removed. This sets up for insertion in descending order.
  • Once the stack is empty, begin inserting each removed element back in the right position.
  • The sortedInsert helper method checks if the stack is empty or if the element to insert is larger than the current top. If so, it pushes the element back onto the stack.
  • If the element is smaller, it temporarily removes the top element, recursively calls sortedInsert, and then pushes the temporarily removed item back.
  • After sorting, display the stack to show it's now ordered in descending order.

Java program to sort the elements of the stack

Below is the Java program to sort the elements of the stack in descending order using recursive approach ?

import java.util.Stack;
public class StackSorter {
    public static void sortStack(Stack<Integer> stack) {
        if (!stack.isEmpty()) {
            int top = stack.pop(); // Remove the top element
            sortStack(stack); // Sort remaining stack recursively
            sortedInsert(stack, top); // Insert the removed item back in sorted order
        }
    }
    // Helper method
    public static void sortedInsert(Stack<Integer> stack, int element) {
        // Insert element when stack is empty or element is greater than top
        if (stack.isEmpty() || element > stack.peek()) {
            stack.push(element);
            return;
        }
        int temp = stack.pop();
        sortedInsert(stack, element);
        stack.push(temp); // Place the held-back element on top
    }
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(4);
        stack.push(2);
        stack.push(9);
        stack.push(7);
        System.out.println("Original Stack: " + stack);
        sortStack(stack);
        System.out.println("Sorted Stack in Descending order: " + stack);
    }
}

Output

Original Stack: [4, 2, 9, 7]
Sorted Stack in Descending order: [9, 7, 4, 2]

Time Complexity: O(N2)

Space Complexity: O(N)

Code explanation

In the above program, we will sort a stack in descending order using recursion. First, it removes each element one by one until the stack is empty. Then, using the sortedInsert helper function, each removed element is inserted back in its correct position to maintain descending order. If the element is larger than the top of the stack, it's pushed back; otherwise, the function pops the top element temporarily, inserts the element, and pushes the popped item back. Finally, the sorted stack is printed, showing elements arranged from highest to lowest.

Updated on: 2024-10-30T18:36:32+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements