Sorting of Stack in Java

Connect with

Sorting of Stack in JavaLearn sorting of stack in Java. Java example to sort elements in stack. I have used built-in Stack from java.util.Stack. Sorting of Integer value of java.util.Stack.

1. Overview of sorting of Stack in Java

Well, when I heard the first time about sorting of the stack, I thought why we required to sort of any stack. Initially, I thought, this is rubbish and time passing thing, but later point in time, realize, this can be an interview question. In fact, most of the interviewer asks this question, how to sort stack in Java or your preferred language. I have written a Java program or example for sorting a Stack in Java.

2. 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;
  }

}

3. Output of stack sorting

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

4. Reference

I hope you enjoyed this post of sorting of a stack in Java, and you can visit design patterns tutorial for more details

Visit Wiki page for behavioral design patterns.
Suggestions or comments are welcome to improve this post. cheers


Connect with

Leave a Comment

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