javaScript
function sort(arr) {
let left = 0, right = arr.length - 1;
if(arr.length === 1 || arr.length === 0) {
return arr;
}
let mid = (left + right) >> 1;
let leftArray = sort(arr.slice(left, mid + 1));
let rightArray = sort(arr.slice(mid + 1));
return merge(arr, leftArray, rightArray)
}
function merge(arr, leftArray, rightArray) {
let leftLength = leftArray.length, leftIndex = 0;
let rightLength = rightArray.length, rightIndex = 0;
while(leftIndex < leftLength && rightIndex < rightLength) {
if(leftArray[leftIndex] < rightArray[rightIndex]) {
arr[leftIndex + rightIndex] = leftArray[leftIndex];
leftIndex++;
} else {
arr[leftIndex + rightIndex] = rightArray[rightIndex];
rightIndex++;
}
}
while(leftIndex < leftLength) {
arr[leftIndex + rightIndex] = leftArray[leftIndex];
leftIndex++;
}
while(rightIndex < rightLength) {
arr[leftIndex + rightIndex] = rightArray[rightIndex];
rightIndex++;
}
return arr;
}
console.log(sort([5,3,8,4,2,7,1,6]))