Forum Moderators: open

Message Too Old, No Replies

Help split an array into two arrays

         

zero3ree

8:29 pm on Dec 7, 2009 (gmt 0)

10+ Year Member



How should I write this function to get the array var to be cut in half.
The merge function is separate I just cant get this function to operate.

function newsort(array){
var alength= array.length;
if (alength <= 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);
var end = (array.length - mid);
var right = new Array(end);
newsort(left)
newsort(right)
result = merge(left, right);

document.writeln("result: " + result + "<br />");
}
return result
}

Fotiman

9:37 pm on Dec 7, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You might want to look at Array methods:
slice
splice

In your example, your left and right arrays are empty. Presumably, though, you want something more like this:

var left = array.slice(0,mid);
var right = array.slice(mid);

zero3ree

9:54 pm on Dec 7, 2009 (gmt 0)

10+ Year Member



Thanks that did it. I looked at the slice and thought that the index points had to be exact in the samples I saw. Thank you.