Skip to content

Instantly share code, notes, and snippets.

@okovalov
Last active February 26, 2019 22:57
Show Gist options
  • Save okovalov/22aac245b35e0e8c8b3d1632bf52abb8 to your computer and use it in GitHub Desktop.
Save okovalov/22aac245b35e0e8c8b3d1632bf52abb8 to your computer and use it in GitHub Desktop.
const mergeSort = arr => {
if (arr.length < 2) return arr
const middleIdx = Math.floor(arr.length / 2)
let left = arr.splice(0, middleIdx)
let right = arr.splice(0)
return merge(mergeSort(left), mergeSort(right))
}
const merge = (arr1, arr2) => {
const res = []
while (arr1.length && arr2.length) {
if (arr1[0] < arr2[0]) {
res.push(arr1.splice(0, 1)[0])
continue
}
res.push(arr2.splice(0, 1)[0])
}
return res.concat(arr1, arr2)
}
const arr = [4,1,6,-9,3,2,8,-7,7]
const res = mergeSort(arr);
console.time('test')
console.log('res', res) // [ -9, -7, 1, 2, 3, 4, 6, 7, 8 ] test: 0.607ms
console.timeEnd('test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment