Sort Elements of a Given Stack in Ascending Order



In this tutorial, you'll learn how to sort the elements of a stack in ascending order using Java. Stacks are fundamental data structures in computer science, operating on a Last-In-First-Out (LIFO) principle.

We break down a simple yet effective method using an additional temporary stack, provide a detailed step-by-step explanation, and include complete code examples. This tutorial is perfect for those looking to enhance their understanding of stack operations and improve their Java programming skills.

Sorting a Stack in Ascending Order Using Java

Stacks are like a pile of books where you can only take the top one off. i.e., s stack stores items in a Last-In-First-Out (LIFO) manner. The last item added is the first one to be removed. Following are the steps to sort the elements of a stack using an auxiliary stack

Step 1: Create a Temporary Stack This is where we'll temporarily hold the sorted elements.

Step 2: Sort the Elements To sort the elements of a stack follow the steps given below

  • While the original stack has items.
  • Take the top item off the original stack.
  • If the temporary stack isn't empty and its top item is bigger than the one you just took, move the temporary stack's items back to the original stack until you can place your item on top.
  • Put the item you took off into the temporary stack.

Step 3: Move Back to Original Stack Once everything is in the temporary stack, move them back to the original stack. Now, they're sorted!

Example

Following is an example

import java.util.Stack;
public class StackSorter {
   public static void sortStack(Stack<Integer> stack) {
      Stack<Integer> tempStack = new Stack<>();

      while (!stack.isEmpty()) {
         int temp = stack.pop();

         while (!tempStack.isEmpty() && tempStack.peek() > temp) {
            stack.push(tempStack.pop());
         }
         tempStack.push(temp);
      }

      while (!tempStack.isEmpty()) {
         stack.push(tempStack.pop());
      }
   }
   public static void main(String[] args) {
      Stack<Integer> stack = new Stack<>();
      stack.push(34);
      stack.push(3);
      stack.push(31);
      stack.push(98);
      stack.push(92);
      stack.push(23);

      System.out.println("Original stack: " + stack);
      sortStack(stack);
      System.out.println("Sorted stack: " + stack);
   }
}

Conclusion

Using another stack, you can easily sort the elements of your stack in ascending order without needing complicated algorithms.

Updated on: 2024-10-23T10:24:03+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements