Merge Sort

Run Settings
LanguageJavaScript
Language Version
Run Command
function mergeSort(arr){ if (arr.length===1){ return arr; } let len= arr.length; let middle= Math.floor(len/2); let left=arr.slice(0,middle); let right=arr.slice(middle); return merge(mergeSort(left), mergeSort(right)); } function merge(left, right){ let leftIndex=0, rightIndex=0; let resultArr=[]; while(leftIndex<left.length&& rightIndex< right.length){ if(left[leftIndex]<right[rightIndex]){ resultArr.push(left[leftIndex]); leftIndex++; } else{ resultArr.push(right[rightIndex]); rightIndex++; } } return resultArr.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); } console.log(mergeSort([2, 8, 1, 3, 6, 7, 5, 4]));
Editor Settings
Theme
Key bindings
Full width
Lines