title: How to code a merge sort algorithm in PHP
body: <p>I've searched a lot for this but I have found nothing so far. I had to ask my question here.</p>
  <p>In my current code I get the result by dividing by 2.</p>
  <p>Sample data : <code>$example = [50,20,87]</code></p>
  <p>Expected result : <code>20,50,87</code></p>
  <p>What I expect is how to do this by dividing by 3 instead of 2</p>
  <p>Here is the code :</p>
  <pre><code>function merge_sort(&amp;$arrayToSort)
  {
      if (sizeof($arrayToSort) &lt;= 1)
          return $arrayToSort;
  
      // split our input array into two halves
      // left...
      $leftFrag = array_slice($arrayToSort, 0, (int)(count($arrayToSort)/2));
      // right...
      $rightFrag = array_slice($arrayToSort, (int)(count($arrayToSort)/2));
  
      // RECURSION
      // split the two halves into their respective halves...
      $leftFrag = merge_sort($leftFrag);
      $rightFrag = merge_sort($rightFrag);
  
      $returnArray = merge($leftFrag, $rightFrag);
  
      return $returnArray;
  }
  
  
  function merge(&amp;$lF, &amp;$rF)
  {
      $result = array();
  
      // while both arrays have something in them
      while (count($lF)&gt;0 &amp;&amp; count($rF)&gt;0) {
          if ($lF[0] &lt;= $rF[0]) {
              array_push($result, array_shift($lF));
          }
          else {
              array_push($result, array_shift($rF));
          }
      }
  
      // did not see this in the pseudo code,
      // but it became necessary as one of the arrays
      // can become empty before the other
      array_splice($result, count($result), 0, $lF);
      array_splice($result, count($result), 0, $rF);
  
      return $result;
  }
  </code></pre>