function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);
const merge = (leftArr, rightArr) => {
const sorted = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < leftArr.length && rightIndex < rightArr.length) {
if (leftArr[leftIndex] < rightArr[rightIndex]) {
sorted.push(leftArr[leftIndex]);
leftIndex++;
} else if (leftArr[leftIndex] > rightArr[rightIndex]) {
sorted.push(rightArr[rightIndex]);
rightIndex++;
} else {
sorted.push(leftArr[leftIndex]);
sorted.push(rightArr[rightIndex]);
leftIndex++;
rightIndex++;
}
}
return sorted.concat(leftArr.slice(leftIndex), rightArr.slice(rightIndex));
};
return merge(mergeSort(left), mergeSort(right));
}
const unsortedArray = [2,4,3,1,5,6];
const sortedArray = mergeSort(unsortedArray);
console.log(sortedArray);