Question
Re-write displayArrayWithStack to get the same result. public class DisplayArray { int array[] = {25,96,87,41};//input array //display array using recursive function as you can see
Re-write displayArrayWithStack to get the same result.
public class DisplayArray { int array[] = {25,96,87,41};//input array
//display array using recursive function as you can see recursively function is called to print the element till the start and end elemnts are same //it will terminate when start < end public void displayArrayRecursively(int s,int e){ if(s<=e){ displayArrayRecursively(s,e-1); System.out.print(array[e] + " "); } }
//display array using stack function, here intial stack is created with first and last element as a record //every time middle point between start and end is to be find and then two new entries into stack until both start and end are equal to same value //when start == first the value is printed public void displayArrayWithStack(int s,int e){ boolean complete = false;
StackInterface stack = new LinkedStack<>(); stack.push(new Record(s,e));
while(!complete && !stack.isEmpty()){ Record top = stack.pop(); s = top.first; e = top.last;
if(s==e) { System.out.print(array[s] + " "); } else{ int m = s + (e-s) / 2; stack.push(new Record(m+1,e)); stack.push(new Record(s,m)); } }
}
public static void main(String args[]){ DisplayArray da = new DisplayArray();
da.displayArrayRecursively(0,da.array.length-1); System.out.println(); da.displayArrayWithStack(0,da.array.length-1); }
private class Record { private int first, last; private Record(int firstIndex, int lastIndex) { first = firstIndex; last = lastIndex; } // end constructor } }
Need this two class to run the code above
https://codeshare.io/2KkNMX : LinkedStack.java
https://codeshare.io/G8RQwB : StackInterface.java
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started