0

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?

MadHatter
  • 51
  • 3
  • @dkaeae I'd really just like to know if my above calculations are correct--I tried on Code Review and it was suggested that I post on Computer Science. – MadHatter Jul 24 '19 at 07:24
  • We usually discourage "please check whether my answer is correct" questions, as only "yes/no" answers are possible, which won't help you or future visitors. See here and here. – dkaeae Jul 24 '19 at 08:17
  • @dkaeae The original answer is a bit over my head even though I just accepted it--if telling me whether my above logic is correct or not--even just this once in a tiny little comment--is outside the realm of possibility, then can you at least tell me where I could get an answer to this specific question? – MadHatter Jul 24 '19 at 08:24
  • 1
    check how counter depends on n value – Bulat Jul 24 '19 at 13:59

0 Answers0