Created
June 27, 2011 15:26
-
-
Save gvinter/1049091 to your computer and use it in GitHub Desktop.
Merge Sort
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
function merge_sort(a_array) { | |
if (a_array.length < 2) { | |
return a_array; | |
} | |
var mid = parseInt(a_array.length / 2); | |
var left = a_array.slice(0, mid); | |
var right = a_array.slice(mid, a_array.length); | |
return merge(merge_sort(left), merge_sort(right)); | |
} | |
function merge(left, right) { | |
var merged = new Array []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) { | |
merged.push(left.shift()); | |
} else { | |
merged.push(right.shift()); | |
} | |
} | |
while (left.length) { | |
merged.push(left.shift()); | |
} | |
while (right.length) { | |
merged.push(right.shift()); | |
} | |
return merged; | |
} | |
merge_sort(3, 5, 7, 2, 9, 1); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment