Sort the array elements using merge sort algorithm

by Nirmala 2009-07-21 11:58:19

Hi...
To sort the array elements using merge sort algorithm just use this code and call the function.
<script type="text/javascript">
function merge(arr)
{
if(arr.length>1)
{
var first=Math.floor(arr.length / 2);
var second = arr.length - first;
var arr1 = new Array(first);
var arr2 = new Array(second);
for(var i = 0; i < first; i++) {
arr1[i] = arr[i];
}
for(i = first; i < first + second; i++) {
arr2[i - first] = arr[i];
}
merge(arr1);
merge(arr2);
var i=0;
var j=0;
var k=0;
while(arr1.length != j && arr2.length != k) {
if(arr1[j] < arr2[k]) {
arr[i] = arr1[j];
i++;
j++;
}
else {
arr[i] = arr2[k];
i++;
k++;
}
}
while(arr1.length != j) {
arr[i] = arr1[j];
i++;
j++;
}
while(arr2.length != k) {
arr[i] = arr2[k];
i++;
k++;
}
}
}
</script>

Example:
var arr=new Array(4,7,6,25,79,5,2,5,3,1,3,9);
merge(arr);
Output:
1,2,3,3,4,5,5,6,7,9,25,79

Tagged in:

1838
like
1
dislike
0
mail
flag

You must LOGIN to add comments