Skip to content

Instantly share code, notes, and snippets.

@kevinjie
Created January 27, 2022 01:59
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 kevinjie/749bf56df8a33521c6f2d57d83fd1a37 to your computer and use it in GitHub Desktop.
Save kevinjie/749bf56df8a33521c6f2d57d83fd1a37 to your computer and use it in GitHub Desktop.
mergeSort
function sort(originalArray) {
const arr = [...originalArray]
if (arr.length <= 1) {
return arr
}
const middleIndex = Math.floor(arr.length / 2)
const leftArray = arr.slice(0, middleIndex)
const rightArray = arr.slice(middleIndex, arr.length)
const leftSortedArray = sort(leftArray)
const rightSortedArray = sort(rightArray)
return mergeSortedArrays(leftSortedArray, rightSortedArray)
}
function mergeSortedArrays(leftArray, rightArray) {
const sortedArray = []
let leftIndex = 0
let rightIndex = 0
while(leftIndex < leftArray.length && rightIndex < rightArray.length) {
let minElement = null
if (leftArray[leftIndex] < rightArray[rightIndex]) {
minElement = leftArray[leftIndex]
leftIndex += 1
} else {
minElement = rightArray[rightIndex]
rightIndex += 1
}
sortedArray.push(minElement)
}
return sortedArray
.concat(leftArray.slice(leftIndex))
.concat(rightArray.slice(rightIndex))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment