Created
March 25, 2011 16:13
-
-
Save jColeChanged/887107 to your computer and use it in GitHub Desktop.
You asked for a sorting algorithm or a function which merged two arrays.
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 merge(array_one, array_two) | |
{ | |
var new_array_length = array_one.length + array_two.length; | |
var array_three = new Array(new_array_length); | |
var p_one = 0; | |
var p_two = 0; | |
for (var p_three = 0; p_three < new_array_length; p_three++) | |
{ | |
if (array_one.length == p_one) | |
{ | |
array_three[p_three] = array_two[p_two]; | |
p_two++; | |
} | |
else if (array_two.length == p_two) | |
{ | |
array_three[p_three] = array_one[p_one]; | |
p_one++; | |
} | |
else if (array_one[p_one] <= array_two[p_two]) | |
{ | |
array_three[p_three] = array_one[p_one]; | |
p_one++; | |
} | |
else | |
{ | |
array_three[p_three] = array_two[p_two]; | |
p_two++; | |
} | |
} | |
return array_three; | |
} | |
function merge_sort(an_array) | |
{ | |
if (1 == an_array.length) | |
{ | |
return an_array; | |
} | |
else | |
{ | |
var mid = Math.floor(an_array.length / 2); | |
return merge( | |
merge_sort(an_array.slice(0, mid)), | |
merge_sort(an_array.slice(mid, an_array.length))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment