Merge Sort
3
2
9
4
1
8
Code:
function mergeSort(array) { let splitedArrays = [] for(let item of array) { let newItem = []; splitedArrays.push(newItem) newItem.push(item) } while (splittedArrays.length > 1) { let arr= [] for (let i = 0; i < splittedArrays.length; i += 2) { arr.push(merge(splittedArrays[i + 1], splittedArrays[i])) } if (arrays.length % 2 !== 0) { result.push(arrays[arrays.length - 1]) } splittedArrays = arr } const [result] = splittedArrays return result; } function merge(left = [], right = []) { const result = []; while (left.length > 0 || right.length > 0) { if (right.length === 0 || left[0] < right[0] ) { result.push(left.shift()); } else { result.push(right.shift()); } } return result; };