Forum Moderators: open

Message Too Old, No Replies

Help splitting a random array into two arrays

         

zero3ree

10:44 pm on Dec 6, 2009 (gmt 0)

10+ Year Member



I am trying to write a function that will take a random array as a var and split it into two arrays. My problem is I don't know how to show the split. I need to cut the array at the mid index. How do i write that so no matter what the length is the middle of the index is selected.

zero3ree

11:12 pm on Dec 6, 2009 (gmt 0)

10+ Year Member



Here is what I have so far and it is not displaying any integers in the html.


function newsort(array){
if (array.length <= 1) {
// an array of length 1 is already sorted

document.writeln("At 1: " + array + "<br />");
return array
}
else {
// divide the array in half, sort them separately
// and then merge them back together
var mid = (array.length / 2);
var left = new Array(mid.length);
var end = (array.length - mid.length);
var right = new Array(end.length);
newsort(left)
newsort(right)
result = merge(left, right);

document.writeln("result: " + result + "<br />");
}
return result
}
function merge(ar1, ar2){
tlength = ar1.length + ar2.length;
//this new array sets the length of the new array to total both arrays being merged
arr3 = new Array(tlength);
firstcounter = 0;
secondcounter = 0;
for (i = 0; i < arr3.length; i++) {
// this if else statement decides whether to take next smallest number from
// first array or second.
if ((secondcounter == ar2.length) ¦¦
((firstcounter < ar1.length) &&
(ar1[firstcounter] < ar2[secondcounter]))) {
arr3[i] = ar1[firstcounter];
firstcounter++;
}
else {
arr3[i] = ar2[secondcounter];
secondcounter++;
}
}
return arr3;
}

And the html

[code]
<html>
<head>
<title>Array Sort</title>
<script src="newsort.js" language="JavaScript" type="text/javascript"></script>
</head>
<body>
<h4>New sorted array:</h4>
<script>
var randomArray = [4, 3, 2, 1];
document.writeln("randomArray: " + randomArray + "<br />");
var sortedArray = newsort(randomArray);
document.writeln("sortedArray: " + sortedArray + "<br />");
</script>
</body>
</html>

Any help is appreciated.