Question - Three stacks can be used to sort a list of numbers.
Assuming stack in holds the input list of numbers,
stack out is to hold the output list after sorting the numbers and
temp is used during the sorting process. The sorting algorithm follows.

1 set up stack in and print it
2 while stack in is not empty repeat
2.1 max = in.pop
2.2 while there are still element in stack in repeat
2.2.1 value = in.pop
2.2.2 if value > max
2.2.2.1 temp.push(max)
2.2.2.2 max = value
2.2.3 else
2.2.3.1 temp.push(value)

2.3 in = temp
2.4 out.push(max)
2.5 temp.clear
3 print sorted stack
---------------------------------------------------------------------------------------------------------------------------------------------------
Answer -

import java.util.*;
import java.io.*;
import javax.swing.JOptionPane;

class SortStack {

   public static void main(String[] args)
   {
    	LinkedList <Integer> sortIn = new LinkedList <Integer>();
    	LinkedList <Integer> sortOut = new LinkedList <Integer>();
    	LinkedList <Integer> sortTemp = new LinkedList <Integer>();
 
    	//A Single Random Object Is Being Used 
    	Random SortNum = new Random();
    	
    	for (int i=1; i<=20; i++)
    		{    		
      			int sortInt = SortNum.nextInt(50);  
      			sortIn.add(sortInt);
      			
      			//Display Dialog Meesage Before Sort
      			JOptionPane.showMessageDialog(null,"Before Sort " + sortIn,"Assignment",JOptionPane.INFORMATION_MESSAGE);
      		}
    
   			System.out.println("Random Number :");
   			System.out.println(sortIn);
   					      
   		//To Check Stack Is Empty
    	while (!sortIn.isEmpty())
   		{
   			int max = sortIn.pop();
   	
   				while (!sortIn.isEmpty())
   				{   			
   					int value = sortIn.pop();
 
   					//Find  The Max Value
   					if (value>max)
   					{
   						sortTemp.push(max);
   						max = value;
   					}
   					else 
   					{
   						sortTemp.push(value);
   					}
   				}
   				
  			sortIn.addAll(sortTemp);
   			sortOut.push(max);
   			sortTemp.clear();
   			
   			//Display Dialog Message After Sort
   			JOptionPane.showMessageDialog(null,"After Sort " + sortOut,"Assignment",JOptionPane.INFORMATION_MESSAGE);
   		}  						
  			//Display The Output
   			System.out.println();
   			System.out.println("Sorted Output :");
   			System.out.println(sortOut);
   			
   }//End Of Main
}//End of Class

----------------------------------------------------------------------------------------------------------------------------------------------------
PS - is there any ways that i can simplify this codes and
it is complicated and confusing as well.

Question

:'(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.