Question

Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks...

Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks only, No other data structures are allowed)

My professor gave us a hint on how to implement this, however she wants the comparable interface to be used. im not sure on how to do this.

Hint: May want to use a public method that accepts the original stack and then creates the two additional stacks needed. This method then calls a private method that accepts all three stacks and does the recursive sort. Your methods should make sure all types of stacks passed contain comparable objects. Refer to the generic presentation in Shared Files.

What I have : unboundedarray.java

import java.util.ArrayList;


public class UnboundedStack
{
   protected ArrayList element;

   public UnboundedStack()
   {
     element = new ArrayList();
   }

   public T peek() throws StackUnderflowException
   {
     T topofstack = null;
     if(isEmpty())
     {
         throw new StackUnderflowException("Empty Stack");
     }
   
     else
         topofstack = element.get(element.size() - 1);
     return topofstack;
   }

   public void pop() throws StackUnderflowException
   {
     if(isEmpty())
     {
       throw new StackUnderflowException("empty stack");
     }
     else
         element.remove(element.size() - 1);
   }

   public void push(T elements) throws StackOverFlowException
   {
      element.add(elements);
   }

   public boolean isEmpty()
   {
      return (element.size() == 0);
   }

   public boolean isFull()
   {
     return false;
   }
}

my main class :

public class Recursivestack {

  
  
    public static UnboundedStack initializeSort(UnboundedStack s)
    {
        UnboundedStack temp = new UnboundedStack<>();
        UnboundedStack sort = new UnboundedStack<>();
        return temp; // this will need to be fixed
    }
  
  
  
  
    public static void main(String args[])
   {
       UnboundedStack unsorted = new UnboundedStack<>();
       unsorted.push("kevin");
       unsorted.push("brian");
       unsorted.push("devon");
       unsorted.push("larry");
       unsorted.push("kaiden");
       initializeSort(unsorted);
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Class UnboundedStack :

import java.util.ArrayList;

public class UnboundedStack<T> implements Comparable
{

protected ArrayList<T> element;
public UnboundedStack()
{
element = new ArrayList<>();
}

public ArrayList getElement() {
return element;
}
public T peek() throws RuntimeException
{
T topOfStack;
if(isEmpty())
{
throw new RuntimeException("StackUnderFlow Exception. Empty Stack");
}

else
topOfStack = (T) element.get(element.size() - 1);
return topOfStack;
}
public T pop() throws RuntimeException
{
if(isEmpty())
{
throw new RuntimeException("StackUnderFlow Exception. Empty stack");
}
else {
T popElement = (T) peek();
element.remove(element.size() - 1);
return popElement;
}
}
public void push(T elements) throws RuntimeException
{
element.add(elements);
}

public boolean isEmpty()
{
return (element.size() == 0);
}

@Override
public int compareTo(Object o) {
if(o.hashCode() == peek().hashCode()) {
return 0;
}else if(peek().hashCode() > o.hashCode()){
return 1;
}else{
return -1;
}
}
}

********************************************************************************************************

Class Sort :

public class Sort<T> {

// Method to sort stack
public void sortStack(UnboundedStack<T> stack){

// If stack is not empty
if(!stack.isEmpty()){

// Remove the top item
final T temp = stack.pop();

// Sort remaining stack
sortStack(stack);

// Push the top item back in sorted stack
sortedInsert(stack, temp);
}
}

// Recursive Method to insert an item x in sorted way
public void sortedInsert(UnboundedStack<T> stack, final T element){
int result = 2;
if(!stack.isEmpty()){
result = stack.compareTo(element);
}
// Base case: Either stack is empty or newly inserted
// item is greater than top (more than all existing)
if(stack.isEmpty() || result == -1){
stack.push(element);
return;
}
// If top is greater, remove the top item and recurse
final T temp = stack.pop();
sortedInsert(stack, element);

// Put back the top item removed earlier
stack.push(temp);
}
}

*********************************************************************************************

Main Method :

import java.util.ArrayList;

public class RecursiveStack {

public static void main(String args[]) {
Sort<String> sortStringStack = new Sort<>();
UnboundedStack<String> unsortedStringStack = new UnboundedStack<>();
unsortedStringStack.push("kevin");
unsortedStringStack.push("brian");
unsortedStringStack.push("devon");
unsortedStringStack.push("larry");
unsortedStringStack.push("kaiden");
sortStringStack.sortStack(unsortedStringStack);
ArrayList<String> stringArrayList = unsortedStringStack.getElement();
for (String element : stringArrayList) {
System.out.println(element);
}

Sort<Integer> sortIntegerStack = new Sort<>();
UnboundedStack<Integer> unsortedIntegerStack = new UnboundedStack<>();
unsortedIntegerStack.push(10);
unsortedIntegerStack.push(1);
unsortedIntegerStack.push(3);
unsortedIntegerStack.push(12);
unsortedIntegerStack.push(12);
unsortedIntegerStack.push(-9);
unsortedIntegerStack.push(88);
unsortedIntegerStack.push(0);
unsortedIntegerStack.push(5);
sortIntegerStack.sortStack(unsortedIntegerStack);
ArrayList<Integer> integerArrayList = unsortedIntegerStack.getElement();
for (Integer element : integerArrayList) {
System.out.println(element);
}

}
}

Add a comment
Know the answer?
Add Answer to:
Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...

    Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The application will be to add large numbers. Review adding large numbers Remember that we can use stacks to safely add integer values that overflow the int data type g. in Java, the maximum possible int value Integer.MAX_VALUE is: 2147483647 so any int addition larger than this will overflow and fail Using stacks to add large numbers safely Will actually represent the large integers to...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

  • I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT