title: Recursive sort in JS
body: <p>I was asked in an interview to write a program/algo to sort an array of number using recursion.</p>
  
  <p>Though I vaguely answered it, I tried and came up with following code:</p>
  
  <p>You can use following <a href="https://jsfiddle.net/RajeshDixit/2u9mLegv/1/" rel="nofollow noreferrer">JSFiddle</a> link to play around.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function sort(arr) {
   if (arr.length === 2) {
     const v1 = arr[0];
      const v2 = arr[1];
      const isGreater = (
       (isString(v1) &amp;&amp; isString(v2) &amp;&amp; v1.toString().toLocaleCompare(v2) &gt; 0) ||
        (isNumber(v1) &amp;&amp; isNumber(v2) &amp;&amp; v1 &gt; v2)
      );
     return isGreater ? [ v2, v1 ] : [ v1, v2 ];
    } else {
     const last = arr.pop();
      const ret = sort(arr);
      const newLast = ret.peekLast();
      
      if (newLast &lt; last) {
        return [ ...ret, last ];
      } else {
       return sort( [ last, ...ret ] );
      }
    }
  }
  
  function isString(value) { return typeof value === 'string'; }
  function isNumber(value) { return Number.isFinite(value); }
  Array.prototype.peekLast = function () { return this.slice().pop(); }
  
  //console.log(sort([1,2,3,4,5]))
  
  console.log(sort([5,4,3,2,1]))</code></pre>
  </div>
  </div>
  </p>
  
  <hr>
  
  <p>The algo I implemented is:</p>
  
  <ul>
  <li>Take the array and check if its length is greater than 2.</li>
  <li>If yes,
  
  <ul>
  <li>Remove last element and store it in a variable.</li>
  <li>Again call same function without last element till it has 2 items.</li>
  <li>Accept array returned from recursive call and peek the last element.</li>
  <li>If <code>newLast</code> value is greater than <code>previousLast</code>
  
  <ul>
  <li>Push <code>previousLast</code> as first element and again call itself with this array.</li>
  </ul></li>
  <li>If not, push <code>previousLast</code> to array and return it. </li>
  </ul></li>
  <li>Else,
  
  <ul>
  <li>For number and string check equality and return correct order.</li>
  <li>For anything else, return same value</li>
  </ul></li>
  </ul>
  
  <hr>
  
  <p>Question is, is there a better way to implement (<em>algo wise</em>)?</p>
  
  <p><strong>Note:</strong> I'm not expecting code improvements. Objective of this question is improvement in algo part or any general stuff I have missed.</p>
  
  <p>I also know, current code does not support:</p>
  
  <ul>
  <li>Sort order. It will sort ascending only.</li>
  <li>May break for Date objects, and does not support Objects in general.</li>
  </ul>
  
  <p>Thanks!</p>