Last active
December 25, 2015 00:39
-
-
Save cstephe/6889839 to your computer and use it in GitHub Desktop.
Merge sort in JS: just keeping fresh with my CS stuff and doing it in JS for fun. So far thsi is memory optimized with merge only being created once just need to do it in-place and it should be even better.
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
var unsorted = [3, 6, 4, 5, 8, 1, 7, 9, 2]; | |
var mergeSort = (function(){ | |
var sort = function (toSort) { | |
var arlength = toSort.length; | |
var midpoint = Math.round(arlength / 2); | |
if (toSort.length > 1) { | |
// better to not slice here since it creates new arrays | |
return merge(mergeSort(toSort.slice(0, midpoint)), | |
mergeSort(toSort.slice(midpoint, arlength))); | |
} | |
return toSort; | |
}; | |
// only want one copy of it | |
var merge = function (sortedA, sortedB) { | |
var toReturn = []; | |
var itA = 0, itB = 0, | |
Alength = sortedA.length, Blength = sortedB.length; | |
while(itA < Alength && itB < Blength) { | |
if (sortedB[itB] < sortedA[itA]) { | |
toReturn.push(sortedB[itB++]); | |
} else { | |
toReturn.push(sortedA[itA++]); | |
} | |
} | |
toReturn = toReturn.concat(sortedB.slice(itB)).concat(sortedA.slice(itA)); | |
return toReturn; | |
}; | |
return sort; | |
})(); | |
console.log(mergeSort(unsorted)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment