Skip to content

Instantly share code, notes, and snippets.

@rajatk16
Created December 18, 2018 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rajatk16/d284af4d8e3f6a07c7b5082ea67d29f1 to your computer and use it in GitHub Desktop.
Save rajatk16/d284af4d8e3f6a07c7b5082ea67d29f1 to your computer and use it in GitHub Desktop.
divide = (array) => {
if (array.length < 2) {
return array
}
const mid = Math.floor(array.length/2)
const smallOne = array.slice(0, mid)
const smallTwo = array.slice(mid)
return sort(divide(smallOne), divide(smallTwo))
}
sort = (smallOne, smallTwo) => {
const sorted = []
while(smallOne.length && smallTwo.length) {
if (smallOne[0] <= smallTwo[0]) {
sorted.push(smallOne.shift())
} else {
sorted.push(smallTwo.shift())
}
}
const output = [...sorted, ...smallOne, ...smallTwo]
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment