Skip to content

Instantly share code, notes, and snippets.

@terakilobyte
Last active January 2, 2017 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terakilobyte/84b48943b20f9603aa413880472a502b to your computer and use it in GitHub Desktop.
Save terakilobyte/84b48943b20f9603aa413880472a502b to your computer and use it in GitHub Desktop.
function mergesort (arr) {
let totalOperations = 0
// this is just to debounce the logging
let timeout
function debouncedLog () {
clearTimeout(timeout)
timeout = setTimeout(() => console.log(`${totalOperations} operations`), 500)
}
function split (unsorted) {
totalOperations++
if (unsorted.length < 2) {
totalOperations++
// the array is either length 0 or 1, so it must already be sorted
return unsorted
}
// find the middle index of this array
let mid = Math.floor(unsorted.length / 2)
totalOperations++
// split the array in half
let left = unsorted.slice(0, mid)
totalOperations++
// get the other half
let right = unsorted.slice(mid, unsorted.length)
totalOperations++
return merge(split(left), split(right))
}
function merge (left, right) {
totalOperations++
// console.log(left, right)
let sorted = []
let il = 0
let ir = 0
while (il < left.length && ir < right.length) {
totalOperations++
if (left[il] <= right[ir]) {
sorted.push(left[il++])
} else {
sorted.push(right[ir++])
}
}
debouncedLog()
totalOperations++
return sorted.concat(left.slice(il)).concat(right.slice(ir))
}
// kick the whole thing off
return split(arr)
}
module.exports = mergesort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment