title: sorting elements of stack using javascript
body: <p>I m trying to understand sorting a stack elements using recursion given in 
  <a href="http://www.geeksforgeeks.org/sort-a-stack-using-recursion/" rel="nofollow noreferrer">http://www.geeksforgeeks.org/sort-a-stack-using-recursion/</a>
  Use of any loop constructs like while, for..etc is not allowed. We can only use the following ADT functions on Stack S:</p>
  
  <p>is_empty(S)  : Tests whether stack is empty or not.</p>
  
  <p>push(S)      : Adds new element to the stack.</p>
  
  <p>pop(S)       : Removes top element from the stack.</p>
  
  <p>top(S)       : Returns value of the top element. Note that this
                 function does not remove element from the stack.
  I tried below but getting error</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var stack = [-3, 14, 18, -5, 30];
  
  function sortStack() {
    if (stack.length &gt; 0) {
      temp = stack.pop();
      sortStack();
      sortedInsert(temp, stack);
    }
  }
  
  function sortedInsert(element, stack) {
    if (stack.length &gt; 0 || element &gt; stack[stack.length - 1]) {
      stack.push(element);
    } else {
      temp = stack.pop();
      sortedInsert(element, stack);
      stack.push(temp);
    }
  
  }
  
  sortStack();
  
  console.log(stack);</code></pre>
  </div>
  </div>
  </p>
  
  <pre><code>RangeError: Maximum call stack size exceeded
  at sortedInsert:12:22
  at sortedInsert:21:5
  at sortedInsert:21:5
  at sortedInsert:21:5
  at sortedInsert:21:5
  at sortedInsert:21:5
  </code></pre>