Popular Posts

June 14, 2024

Java Program to Sort a Stack Using a Temporary Stack

 

Java Program: 

How to sort a Stack using a temporary Stack?

Description:
You have a stack with full of integers. Sort it in the ascending order using another temporary array by using all stack functionality.

Code:

package com.java2novice.algo;

import java.util.Stack;

public class StackSort {

    public static Stack<Integer> sortStack(Stack<Integer> input){
        
        Stack<Integer> tmpStack = new Stack<Integer>();
        System.out.println("=============== debug logs ================");
        while(!input.isEmpty()) {
            int tmp = input.pop();
            System.out.println("Element taken out: "+tmp);
            while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) {
                input.push(tmpStack.pop());
            }
            tmpStack.push(tmp);
            System.out.println("input: "+input);
            System.out.println("tmpStack: "+tmpStack);
        }
        System.out.println("=============== debug logs ended ================");
        return tmpStack;
    }
    
    public static void main(String a[]){
        
        Stack<Integer> input = new Stack<Integer>();
        input.add(34);
        input.add(3);
        input.add(31);
        input.add(98);
        input.add(92);
        input.add(23);
        System.out.println("input: "+input);
        System.out.println("final sorted list: "+sortStack(input));
    }
}

Output:

input: [34, 3, 31, 98, 92, 23]
=============== debug logs ================
Element taken out: 23
input: [34, 3, 31, 98, 92]
tmpStack: [23]
Element taken out: 92
input: [34, 3, 31, 98]
tmpStack: [23, 92]
Element taken out: 98
input: [34, 3, 31]
tmpStack: [23, 92, 98]
Element taken out: 31
input: [34, 3, 98, 92]
tmpStack: [23, 31]
Element taken out: 92
input: [34, 3, 98]
tmpStack: [23, 31, 92]
Element taken out: 98
input: [34, 3]
tmpStack: [23, 31, 92, 98]
Element taken out: 3
input: [34, 98, 92, 31, 23]
tmpStack: [3]
Element taken out: 23
input: [34, 98, 92, 31]
tmpStack: [3, 23]
Element taken out: 31
input: [34, 98, 92]
tmpStack: [3, 23, 31]
Element taken out: 92
input: [34, 98]
tmpStack: [3, 23, 31, 92]
Element taken out: 98
input: [34]
tmpStack: [3, 23, 31, 92, 98]
Element taken out: 34
input: [98, 92]
tmpStack: [3, 23, 31, 34]
Element taken out: 92
input: [98]
tmpStack: [3, 23, 31, 34, 92]
Element taken out: 98
input: []
tmpStack: [3, 23, 31, 34, 92, 98]
=============== debug logs ended ================
final sorted list: [3, 23, 31, 34, 92, 98].

No comments:
Write comments