Skip to content

Instantly share code, notes, and snippets.

@andresabello
Last active June 7, 2020 03:16
Show Gist options
  • Save andresabello/6d359ee4bc4236c76fe977fffa728c01 to your computer and use it in GitHub Desktop.
Save andresabello/6d359ee4bc4236c76fe977fffa728c01 to your computer and use it in GitHub Desktop.
merge-sort algorithm using Javascript
const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];
function mergeSort(array) {
if (array.length === 1) {
return array
}
let half = array.length / 2
let left = array.slice(0, half)
let right = array.slice(half)
return merge(
mergeSort(left),
mergeSort(right)
)
}
function merge(left, right) {
let result = []
let leftIndex = 0
let rightIndex = 0
while(leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex])
leftIndex++
}else {
result.push(right[rightIndex])
rightIndex++
}
}
return result.concat(left.slice(leftIndex), right.slice(rightIndex))
}
mergeSort(numbers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment