I am trying to calculate the time complexity of an algorithm using n
in the code below.
I have a working solution to a coding challenge to sort a stack using only another stack, and I've added a counter variable n
that is incremented anywhere an element in the stack is pushed, popped, or held.
The following code is written in JavaScript:
const sortStack = (stack) => {
let n = 0;
sorted = new Stack();
while (stack.storage.length) {
tmp = stack.pop();
n += 1;
if (tmp >= sorted.peek()) {
sorted.push(tmp);
n += 1;
} else {
while (tmp < sorted.peek()) {
stack.push(sorted.pop());
n += 1;
}
sorted.push(tmp);
n += 1;
}
}
console.log("n: ", n);
return sorted;
}
sortedStack = sortStack(s);
sortedStack.printContents();
If my calculations and usage of n
are correct, then this algorithm has an input n
of 6 (length of stack
) with a final n
of 30, which would give it a time complexity of O(N*5).
Is this correct?