Created
May 16, 2014 21:30
-
-
Save jwchang0206/a2bdd46db3cf9b2bde07 to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
var arr = [6, 5, 3, 1, 8, 7, 2, 4]; | |
function merge(left, right) { | |
var li = 0, | |
ri = 0, | |
arr = []; | |
while (li < left.length && ri < right.length) { | |
if (left[li] < right[ri]) | |
arr.push(left[li++]); | |
else | |
arr.push(right[ri++]); | |
} | |
return arr.concat(left.splice(li)).concat(right.splice(ri)); | |
} | |
function mergeSort(arr) { | |
if (arr.length < 2) return arr; | |
var middle = Math.floor(arr.length / 2), | |
left = arr.splice(0, middle), | |
right = arr; | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
arr = mergeSort(arr); | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment