naveen reddy bathu
naveen reddy bathu

Reputation: 57

what would be the time complexity of this algorithm and why?

could anyone please explain me the time complexity of this code. Thanks

public static Stack<Integer> sortStack(Stack<Integer> aStack) {

    Stack<Integer> rStack=new Stack<>();
    int temp=0;

    rStack.push(aStack.pop());

    while(!aStack.empty()){
        temp=aStack.pop();

        while(!rStack.empty() && temp >rStack.peek()){
            aStack.push(rStack.pop());
        }
        rStack.push(temp);
    }
    return rStack;
}

Upvotes: 0

Views: 72

Answers (1)

S&#233;bastien
S&#233;bastien

Reputation: 308

I think it'd be O(n^2) since the time complexity of the inner while is n and it's the same for the outer while.

Upvotes: 1

Related Questions