Created
January 27, 2022 01:59
-
-
Save kevinjie/749bf56df8a33521c6f2d57d83fd1a37 to your computer and use it in GitHub Desktop.
mergeSort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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