Question

For merge sort the time complexity is Θ(nlogn), but what if we had two unsorted stacks...

For merge sort the time complexity is Θ(nlogn),

but what if we had two unsorted stacks and wanted to but merge them into one final sorted stack! what is the time complexity then?

code

/ Java program to merge to unsorted stacks

// into a third stack in sorted way.

import java.io.*;

import java.util.*;

  

public class GFG {

      

    // This is the temporary stack

    static Stack<Integer> res = new Stack<Integer>();

    static Stack<Integer> tmpStack = new Stack<Integer>();

      

    // Sorts input stack and returns

    // sorted stack.

    static void sortStack(Stack<Integer> input)

    {

        while (input.size() != 0)

        {

            // pop out the first element

            int tmp = input.peek();

            input.pop();

      

            // while temporary stack is not empty and

            // top of stack is greater than temp

            while (tmpStack.size() != 0 &&

                            tmpStack.peek() > tmp)

            {

      

                // pop from temporary stack and push

                // it to the input stack

                input.push(tmpStack.peek());

                tmpStack.pop();

            }

      

            // push temp in tempory of stack

            tmpStack.push(tmp);

        }

    }

      

    static void sortedMerge(Stack<Integer> s1,

                                Stack<Integer> s2)

    {

        // Push contents of both stacks in result

        while (s1.size() != 0) {

            res.push(s1.peek());

            s1.pop();

        }

          

        while (s2.size() != 0) {

            res.push(s2.peek());

            s2.pop();

        }

      

        // Sort the result stack.

        sortStack(res);

    }

      

    // main function

    public static void main(String args[])

    {

        Stack<Integer> s1 = new Stack<Integer>();

        Stack<Integer> s2 = new Stack<Integer>();

        s1.push(34);

        s1.push(3);

        s1.push(31);

      

        s2.push(1);

        s2.push(12);

        s2.push(23);

      

        sortedMerge(s1, s2);

        System.out.println("Sorted and merged stack :");

      

        while (tmpStack.size() != 0) {

            System.out.print(tmpStack.peek() + " ");

            tmpStack.pop();

        }

    }

}

  

// This code is contributed by Manish Shaw

// (manishshaw1)

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

Generally the time complexity of the merge sort is O(nlogn) .{n:length of the stack or array}

But here we are considering two stacks let us say s1,s2 are the two stracks of length n,m

as per the question

1.we have to join or add the two stacks S1+S2 = Stack

n+m : length of the resultant Stack

2. As we know that to merge any stack or array of a particular length then the time complexity will be O(nlogn). here

n+m = length of the resultant Stack.

so, time complexity is O((m+n)log(m+n)).

Add a comment
Know the answer?
Add Answer to:
For merge sort the time complexity is Θ(nlogn), but what if we had two unsorted 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
  • 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...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • Please help me to solve the problem with java language! An implementation of the Merge Sort...

    Please help me to solve the problem with java language! An implementation of the Merge Sort algorithm. Modify the algorithm so that it splits the list into 3 sublists (instead of two). Each sublist should contain about n/3 items. The algorithm should sort each sublist recursively and merge the three sorted sublists. The traditional merge sort algorithm has an average and worst-case performance of O(n log2 n). What is the performance of the 3-way Merge Sort algorithm? Merge Sort algorithm...

  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • 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...

  • Implement Merge Sort and test it on a small list of 10 random integer values. c++...

    Implement Merge Sort and test it on a small list of 10 random integer values. c++ please template            // merge-sort S void mergeSort(list& S, const C& less) { typedef typename list::iterator Itor;       // sequence of elements int n = S.size(); if (n <= 1) return;                   // already sorted list S1, S2; Itor p = S.begin(); for (int i = 0; i < n / 2; i++) S1.push_back(*p++);   // copy first half to...

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

    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...

  • Hi All, Can someone please help me correct the selection sort method in my program. the...

    Hi All, Can someone please help me correct the selection sort method in my program. the output for the first and last sorted integers are wrong compared with the bubble and merge sort. and for the radix i have no idea. See program below import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class Sort { static ArrayList<Integer> Data1 = new ArrayList<Integer>(); static ArrayList<Integer> Data2 = new ArrayList<Integer>(); static ArrayList<Integer> Data3 = new ArrayList<Integer>(); static ArrayList<Integer> Data4 = new ArrayList<Integer>(); static int...

  • 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...

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