Skip to content

Instantly share code, notes, and snippets.

@GoodNovember
Created May 30, 2019 16:24
Show Gist options
  • Save GoodNovember/7bf1af19a3d530532beac9a06f042975 to your computer and use it in GitHub Desktop.
Save GoodNovember/7bf1af19a3d530532beac9a06f042975 to your computer and use it in GitHub Desktop.
So, uh. Why did you write it like that?
const MergeSort = ({ unsortedArray }) => {
const { length } = unsortedArray
if (length <= 1) {
return unsortedArray
} else {
const middle = Math.floor(length / 2)
const unsortedLeft = unsortedArray.slice(0, middle)
const unsortedRight = unsortedArray.slice(middle)
const { result: left } = MergeSort({ unsortedArray: unsortedLeft })
const { result: right } = MergeSort({ unsortedArray: unsortedRight })
const { result } = Merge({ left, right })
return { result }
}
}
const Merge = ({ left, right }) => {
const resultArray = []
let leftIndex = 0
let rightIndex = 0
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < rightIndex[rightIndex]) {
resultArray.push(left[leftIndex])
leftIndex++
} else {
resultArray.push(right[rightIndex])
rightIndex++
}
}
const result = resultArray.concat(left.slice(leftIndex)).concat(right.slice(rightIndex))
return { result }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment