/    Sign up×
Community /Pin to ProfileBookmark

Beginner question – sorting

I am trying to write a recursive function that sorts an array. I keep getting a “too much recursion” error in Firefox.

JS code:

function newSort(arr)
{
if (arr.length == 1)
{
return arr;
}
else
{
var low = 0;
var high = arr.length – 1;
var mid = parseInt((low + high) / 2);
var left = new Array(mid);
var right = new Array(arr.length – mid);

for (var i = 0; i < mid; i++)
{
left[i] = arr[i];
}

var counter = 0;
for (var i = mid; i < arr.length; i++)
{
right[counter] = arr[i];
counter++;
}
newSort(left);
newSort(right);
var result = merge(left, right)
return result;

}

function merge(a1, a2)
{
var a3 = new Array();
var i = 0;

while (a1.length != 0 && a2.length != 0)
{
if (a1[0] < a2[0])
{
a3[i] = a1.shift();
}
else
{
a3[i] = a2.shift();
}
i++;
}

// Concatenate remaining elements
if (a1.length == 0)
{
a3 = a3.concat(a2);
}
else if (a2.length == 0)
{
a3 = a3.concat(a1);
}
return a3;

}

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@A1ien51Jul 14.2008 — Reason you are not using sort()? http://www.javascriptkit.com/javatutors/arraysort.shtml

Eric
Copy linkTweet thisAlerts:
@JamesEngleauthorJul 14.2008 — I am experimenting with things just trying to learn.
×

Success!

Help @JamesEngle spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...