function mergeSort(arr) {
if (arr.length <= 1) {
return arr
}
const middleIndex = Math.floor(arr.length / 2)
const leftArray = arr.slice(0, middleIndex)
const rightArray = arr.slice(middleIndex)
return merge(mergeSort(leftArray), mergeSort(rightArray))
}
function merge(leftArray, rightArray) {
let sortedArray = []
while (leftArray.length && rightArray.length) {
if (leftArray[0] < rightArray[0]) {
sortedArray.push(leftArray.shift())
} else {
sortedArray.push(rightArray.shift())
}
}
if (leftArray.length) {
sortedArray = sortedArray.concat(leftArray)
}
if (rightArray.length) {
sortedArray = sortedArray.concat(rightArray)
}
return sortedArray
}
const arr = [2, 3, 41, 1, 6, 53, 4, 6, 87, 4]
const res = mergeSort(arr)
console.log(res)
console