Question

Use the TestTime.java/TestTime.cpp le to compare the two queue implementations. Note that enqueue function when implemented...

Use the TestTime.java/TestTime.cpp le to compare the two queue implementations. Note that enqueue function when implemented using an array has O(1) complexity, and when using two arrays has O(n) complexity, where n is the current size of the queue. So, the two stack implementation should take more time, which is substantiated by the experiment (time output).

public class TestTime {

   public static void main(String[] args) throws Exception {
       for (int maxSize = 10000; maxSize <= 50000; maxSize += 10000) {

           QueueUsingStack qViaStack = new QueueUsingStack(maxSize);
           long startTime = System.currentTimeMillis();
           for (int i = 0; i < maxSize; i++) {
               qViaStack.enqueue(i);
           }
           for (int i = 0; i < maxSize; i++) {
               qViaStack.dequeue();
           }
           long endTime = System.currentTimeMillis();
           System.out.printf("Time taken for %d enqueue/dequeue operations, when using a stack implementation: %d\n",
                   2 * maxSize, (endTime - startTime));
       }
       System.out.println();

       for (int maxSize = 1000000; maxSize <= 5000000; maxSize += 1000000) {

           Queue queue = new Queue(maxSize);
           long startTime = System.currentTimeMillis();
           for (int i = 0; i < maxSize; i++) {
               queue.enqueue(i);
           }
           for (int i = 0; i < maxSize; i++) {
               queue.dequeue();
           }
           long endTime = System.currentTimeMillis();
           System.out.printf("Time taken for %d enqueue/dequeue operations, when using an array implementation: %d\n",
                   2 * maxSize, (endTime - startTime));
       }
   }
}

YOU SHOULD GET THE FOLLOWING OUTPUTS:

Time taken for 20000 enqueue/dequeue operations, when using a stack implementation: 221
Time taken for 40000 enqueue/dequeue operations, when using a stack implementation: 690
Time taken for 60000 enqueue/dequeue operations, when using a stack implementation: 1160
Time taken for 80000 enqueue/dequeue operations, when using a stack implementation: 1845
Time taken for 100000 enqueue/dequeue operations, when using a stack implementation: 2881
Time taken for 2000000 enqueue/dequeue operations, when using an array implementation: 11
Time taken for 4000000 enqueue/dequeue operations, when using an array implementation: 20
Time taken for 6000000 enqueue/dequeue operations, when using an array implementation: 12
Time taken for 8000000 enqueue/dequeue operations, when using an array implementation: 13
Time taken for 10000000 enqueue/dequeue operations, when using an array implementation: 16

Homework Answers

Answer #1

// Queue.java : Java program to implement queue using a single array

public class Queue {

      

       private int front;

       private int rear;

       private int queue[];

      

       // create an empty queue of maximum size maxSize

       public Queue(int maxSize)

       {

             queue = new int[maxSize];

             rear = -1;

             front = -1;

       }

      

       // method to insert an element at the end of the queue

       public void enqueue(int val)

       {

             // check if queue is not full, then insert the element at the end of the queue

             if(rear < (queue.length-1))

             {

                    rear++; // increment rear

                    queue[rear] = val; // insert val as last element of queue

                    // if queue was empty set front to rear

                    if(front == -1)

                           front = rear;

             }

       }

      

       // method to delete the front element from queue

       public void dequeue()

       {

             if(front <= rear) // check if queue is not empty

             {

                   

                    front++; // increment front

                    // if queue is empty, set front and rear to -1

                    if(front > rear)

                    {

                           front = -1;

                           rear = -1;

                    }

                   

              }

            

       }

      

}

//end of Queue.java

// QueueUsingStack.java : Java program to implement Queue operations using 2 stacks(arrays)

public class QueueUsingStack {

       private int top;

       private int stack1[];

       private int stack2[];

       // create an empty stack of maximum size maxSize

       public QueueUsingStack(int maxSize)

       {

             stack1= new int[maxSize];

             top = -1;

       }

      

       // method to insert an element at the end of queue

       public void enqueue(int val)

       {

             if(top < (stack1.length-1)) // check if stack is not full, insert the element as the top element

             {

                    top++; // increment the top

                    stack1[top] = val; // insert the element

                    //System.out.println("Top = "+top);

             }

       }

      

       // method to delete the front element from queue

       public void dequeue()

       {

             if(top != -1) // if stack is not empty

             {

                    // create stack2 of size top+1

                    stack2 = new int[top+1];

                    // insert elements from top to end from stack 1 to stack 2

                    for(int i=top,j=0;i>=0;i--,j++)

                    {

                           stack2[j] = stack1[i];

                    }

                   

                    top--; // remove the front element

                   

                    // insert the elements back from stack2 to stack2 , removing the front element

                    for(int i=top,j=0;i>=0;i--,j++)

                    {

                           stack1[j] = stack2[i];

                    }

                   

             }

            

       }

      

}

//end of QueueUsingStack.java

//TestTime.java

public class TestTime {

      

       public static void main(String[] args) throws Exception {

              for (int maxSize = 10000; maxSize <= 50000; maxSize += 10000) {

                  QueueUsingStack qViaStack = new QueueUsingStack(maxSize);

                  long startTime = System.currentTimeMillis();

                  for (int i = 0; i < maxSize; i++) {

                      qViaStack.enqueue(i);

                  }

                  for (int i = 0; i < maxSize; i++) {

                      qViaStack.dequeue();

                  }

                  long endTime = System.currentTimeMillis();

                  System.out.printf("Time taken for %d enqueue/dequeue operations, when using a stack implementation: %d\n",

                          2 * maxSize, (endTime - startTime));

              }

              System.out.println();

              for (int maxSize = 1000000; maxSize <= 5000000; maxSize += 1000000) {

                  Queue queue = new Queue(maxSize);

                  long startTime = System.currentTimeMillis();

                  for (int i = 0; i < maxSize; i++) {

                      queue.enqueue(i);

                  }

                  for (int i = 0; i < maxSize; i++) {

                      queue.dequeue();

                  }

                  long endTime = System.currentTimeMillis();

                  System.out.printf("Time taken for %d enqueue/dequeue operations, when using an array implementation: %d\n",

                          2 * maxSize, (endTime - startTime));

              }

          }

}

//end of TestTime.java

Output:

Know the answer?
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
Similar Questions
A Queue is a linked list with pointers to both the head of the list as...
A Queue is a linked list with pointers to both the head of the list as well as the tail (or the last element) of the list. Given a queue Q, Q.head gives the head of the queue and Q.tail gives the tail of the queue. Give O(1) time algorithms for the following tasks. Enqueue • Input: A queue Q of distinct integers and a queue element a not in Q. 1 • Output: Q with the element a added...
Restricted structures such as stack and queue are fast, but they do not support access in...
Restricted structures such as stack and queue are fast, but they do not support access in the key field mode. Group of answer choices True False Big O analysis evaluates an algorithm based on its _________ performance. Group of answer choices A. average-case B. best-case C. worst-case Which of the following algorithms is the fastest in speed? Group of answer choices A. Polynomial time algorithm B. Linear time algorithm C. Exponential time algorithm The following code gives an implementation of...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract method called makeStack that returns a Stack of Strings. Use the Stack interface as the return type, not a specific implementation! Write a class named NodeStackTest that extends your AbstractStackTest class. Implement the makeStack method to return a NodeStack. Repeat parts 1 and 2 for the Queue interface and the NodeQueue implementation. Write a new stack implementation, ArrayStack. It should be generic and use...
There is a Java program that is missing one recursive function: public class Fibonacci { /*...
There is a Java program that is missing one recursive function: public class Fibonacci { /* / 0 when n = 0 * fib(n) = | 1 when n = 1 * \ fib(n-1)+fib(n-2) otherwise */ public static int fib(int n) { return 0; } /* Fibonacci Test Framework * * Note, this takes a long time to compute fib(44). */ public static void main(String[] args) { int[] input = { 11, 22, 33, 44}; int[] expect = { 89,...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number in A and an O(log n)-time computation for each odd number in A. What is the best-case running time of Algorithm X? What is the worst-case running time of Algorithm X? 2. Given an array, A, of n integers, give an O(n)-time algorithm that finds the longest subarray of A such that all the numbers in that subarray are in sorted order. Your algorithm...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads in a sequence of strings from standard input using StdIn.readString() , and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 k N , where N is the number of string on standard input. The running time of the program must be linear in the size of...
Note: Do not use classes or any variables of type string to complete this assignment Write...
Note: Do not use classes or any variables of type string to complete this assignment Write a program that reads in a sequence of characters entered by the user and terminated by a period ('.'). Your program should allow the user to enter multiple lines of input by pressing the enter key at the end of each line. The program should print out a frequency table, sorted in decreasing order by number of occurences, listing each letter that ocurred along...
I need this before the end of the day please :) In Java 10.13 Lab 10...
I need this before the end of the day please :) In Java 10.13 Lab 10 Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you...
Question: I get a Segmentation fault error sometimes when I addElementBack or print. Am I using...
Question: I get a Segmentation fault error sometimes when I addElementBack or print. Am I using pointers correctly and deleting memory properly? #ifndef DYNAMICARRAY_H #define DYNAMICARRAY_H #include <cstdlib> #include <iostream> using namespace std; // Node class class Node { int data; Node* next; Node* prev; public: Node(); Node(int); void SetData(int newData) { data = newData; }; void SetNext(Node* newNext) { next = newNext; }; void SetPrev(Node* newPrev) { prev = newPrev; }; int getData() { return data; }; Node* getNext()...
Strings The example program below, with a few notes following, shows how strings work in C++....
Strings The example program below, with a few notes following, shows how strings work in C++. Example 1: #include <iostream> using namespace std; int main() { string s="eggplant"; string t="okra"; cout<<s[2]<<endl; cout<< s.length()<<endl; ​//prints 8 cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the piece cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl; cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below //cout<<s.append(t[1])<<endl; ​//an error; see Note 1 cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl; if (s.find("gg")!=-1) cout<<"found...