title: Merge sort implementation JavaScript
body: <p>I was trying to implement merge sort algorithm in JavaScript without built in methods like slice(), splice(), etc. It doesn’t work exactly I wish. Can you help me to figure out where is bug hidden? Getting output [3, 5, 5, 3, 7] instead of [3, 5, 5, 7, 8].</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>// Merge Sort implementation
  
  // sort implementation
  function sort(arr, start, mid, end) {
  
    // Creation and filling the temp arrays
    let lArray = [];
    let rArray = [];
  
    for (let i = 0; i &lt;= mid - start; i++) {
      lArray[i] = arr[start + i];
    }
  
    for (let j = 0; j &lt;= end - mid - 1; j++) {
      rArray[j] = arr[mid + 1 + j];
    }
  
  
    // Sorting and updating current array
    let i = 0;
    let j = 0;
    let k = start;
  
    while (i &lt; lArray.length &amp;&amp; j &lt; rArray.length) {
      if (lArray[i] &lt; rArray[j]) {
        arr[k] = lArray[i];
        i++;
        k++;
      } else {
        arr[k] = rArray[j];
        j++;
        k++;
      }
    }
  
    // Handling last element in lArray or rArray
  
    i &lt; lArray.length ? arr[k] = lArray[i] : arr[k] = rArray[j];
  }
  
  // Recursive Merge Sort 
  function recursiveMergeSort(arr, start, end) {
    if (start &lt; end) {
      let mid = Math.floor(((end) + start) / 2);
      //console.log(start, end, mid);
      recursiveMergeSort(arr, start, mid);
      recursiveMergeSort(arr, mid + 1, end);
      sort(arr, start, mid, end);
    }
  }
  
  function mergeSort(arr) {
  
    let start = 0;
    let end = arr.length - 1;
  
    recursiveMergeSort(arr, start, end);
    return (arr)
  }
  
  console.log(mergeSort([5, 8, 3, 7, 5]));</code></pre>
  </div>
  </div>
  </p>