Forum Moderators: open

Message Too Old, No Replies

Help Merging and sorting Arrays

         

zero3ree

6:18 pm on Nov 28, 2009 (gmt 0)

10+ Year Member



I am working with two arrays. I want to take these two arrays and combine them into one array that is sorted. I believe I have the code3 correct but when I run it it says merge is undefined.

Here is my code

function Merge(arr1, arr2){
totallength = arr1.length + arr2.length;
arr3 = new arr[totallength];
firstcounter = 0;
secondcounter = 0;
for (i = 0; i < arr3.length; i++) {
// Deciding whether to take next smallest number from
// first array or second.
if ((secondcounter == arr2.length) ¦¦
((firstcounter < arr1.length) &&
(arr1[firstcounter] < arr2[secondcounter]))) {
arr3[i] = arr1[firstcounter];
firstcounter++;
}
else {
arr3[i] = arr2[secondcounter];
secondcounter++;
}
}
return arr3;
}

Html is simply

<html>
<head>
<title>Array Sort</title>
<script src="sort.js" language="JavaScript" type="text/javascript"></script>
</head>
<body>
<script>
var arr1 = [3, 7, 12, 15, 22, 45, 56];
var arr2 = [1, 2, 5, 17, 20];
merge(arr1, arr2);
</script>
</body>
</html>

zero3ree

7:11 pm on Nov 28, 2009 (gmt 0)

10+ Year Member



Ok that was a dumb mistake on my part. Capital M and lowercase m. Now it is saying that arr is not a defined file. I am trying to set up the perameters of the new array with the total length of arr1 and arr2 I'm not sure why this isn't defined.

zero3ree

9:44 pm on Nov 28, 2009 (gmt 0)

10+ Year Member



Found the problem arr3 = new Array(totallength);

and it worked.