Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Java) Create a java program sorting stack of integers with the smallest number

ID: 3666987 • Letter: #

Question


(Java)
Create a java program sorting stack of integers with the smallest number on top in descending order. One is allowed to use one stack to hold the data and another stack as an auxilliary data structure. Don't use other data structure like array etc for this problem.


(Input): Doesn't need any use input from console, create a random number between 0 to 20 and that should show no. of randoms that that you should be generated as an input.Inputs should be between 0 to 50. For example, if the first random number generated is 10, you need to generated 10 more random numbers and push them into the stack for sorting purpose.

(Useful methods): pop(),push(),isEmpty()

(Output): You first print the content of the stack and then print the sorted item.
for example:

TheRandom Number = 13
Initial Stack: [4, 7, 18, 39, 42, 8, 35, 23, 50, 0, 23, 11, 6]
Sorted Stack: [0, 4, 6, 7, 8, 11, 18, 23, 23, 35, 39, 42, 50]

Using random() or random.math(), please create an original program that would print both the sorted and content stack, Thanks

Explanation / Answer

import java.util.Random;
import java.util.Stack;

public class SortStack {
  
   public static void sort(Stack<Integer> s) {
   if (!s.isEmpty()) {
   Integer t = s.pop();
   sort(s);
   insert(t, s);
   }
   }

   private static void insert(Integer x, Stack<Integer> s) {
   if (s.isEmpty()) {
   s.push(x);
   return;
   }

   if (x < s.peek()) {
   Integer t = s.pop();
   insert(x, s);
   s.push(t);
   } else {
   s.push(x);
   }
   }
  
   public static void main(String[] args) {
       Random random = new Random();
       int randNum = random.nextInt(21);//[0-20]
      
       Stack<Integer> s = new Stack<Integer>();
       for(int i=1; i<=randNum; i++){
           s.push(random.nextInt(51)); //[0-50]
       }
       System.out.println(s.toString());
       sort(s);
       System.out.println(s.toString());
      
   }

}