gistlib
Here's the implementation of Merge Sort in JavaScript using recursion:
index.tsxfunction mergeSort(arr) { if (arr.length <= 1) { return arr; } const middleIndex = Math.floor(arr.length / 2); const leftArr = arr.slice(0, middleIndex); const rightArr = arr.slice(middleIndex); return merge(mergeSort(leftArr), mergeSort(rightArr)); } function merge(leftArr, rightArr) { const resultArr = []; while (leftArr.length && rightArr.length) { if (leftArr[0] < rightArr[0]) { resultArr.push(leftArr.shift()); } else { resultArr.push(rightArr.shift()); } } return resultArr.concat(leftArr, rightArr); } 565 chars26 lines
function mergeSort(arr) { if (arr.length <= 1) { return arr; } const middleIndex = Math.floor(arr.length / 2); const leftArr = arr.slice(0, middleIndex); const rightArr = arr.slice(middleIndex); return merge(mergeSort(leftArr), mergeSort(rightArr)); } function merge(leftArr, rightArr) { const resultArr = []; while (leftArr.length && rightArr.length) { if (leftArr[0] < rightArr[0]) { resultArr.push(leftArr.shift()); } else { resultArr.push(rightArr.shift()); } } return resultArr.concat(leftArr, rightArr); }
To use this Merge Sort implementation, simply call the mergeSort() function and pass in an array:
mergeSort()
index.tsxconst unsortedArr = [5, 2, 6, 3, 1, 4]; const sortedArr = mergeSort(unsortedArr); console.log(sortedArr); // [1, 2, 3, 4, 5, 6] 129 chars5 lines
const unsortedArr = [5, 2, 6, 3, 1, 4]; const sortedArr = mergeSort(unsortedArr); console.log(sortedArr); // [1, 2, 3, 4, 5, 6]
gistlibby LogSnag