Sorting of Stack in Java

Connect with

Oracle JavaWell, when I heard first time about sorting of stack, I thought why we required to sort of any stack. Initially I thought , this is rubbish and time pass thing, but later point of time, realize this can be interview question. In-fact, most of the interviewer ask this question, how to sort stack in java. I tried to demonstrate the exercise of writing program of sorting stack in java.

1. Java Program for Sorting Stack

In this program I have taken in built Stack from java.util.stack package, you can take this your own stack class to sort the input, this completely your choice.


package com.mysoftkey.ds.stack;

import java.util.Iterator;
import java.util.Stack;

/**
 * Demonstration of Java program to sort stack 
 * in ascending order.
 *  
 * @author ranjeet jha
 *
 */
public class SortingStackExample {

  public static void main(String[] args) {

	// create new stack and add elements into it
	Stack stack = new Stack();
	stack.addElement(9);
	stack.addElement(4);
	stack.addElement(1);
	stack.addElement(8);
	stack.addElement(2);
	
	System.out.println(" ==== original stack iteration before sort === ");
	Iterator it = stack.iterator();
	while(it.hasNext()) {
		System.out.println(it.next());
	}
	
	// call method for sorting of originalStack
	Stack sortedStack = sortStack(stack);
	
	System.out.println("sortedStack iteration: ");
	it = sortedStack.iterator();
	while(it.hasNext()) {
   	  System.out.println(it.next());
	}

	}

 /**
  * Java program to sort stack in ascending order.
  *  
  * @param stack
  * @return
  */
  public static Stack sortStack(Stack stack) {
    Stack newStack = new Stack();
	
	// iterate over till filled stack is not empty 
	while (!stack.isEmpty()) {
	 int tmp = stack.pop();
			
	 // iterate and check if newStack.peek value > tmp, 
	 // re-push in original stack from popping new stack
	 while (!newStack.isEmpty() && newStack.peek() > tmp) {
	  stack.push(newStack.pop());
	 }
	 newStack.push(tmp);
	}
	return newStack;
  }

}

Output of Stacking sorting

==== original stack iteration before sort === 
9
4
1
8
2
sortedStack iteration: 
1
2
4
8
9


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *