1
votes

I have a recursive function which bubblesorts through an array in Javascript. The function calls on itself, which results in it exceeding the stack size of the browser and returning the error:

RangeError: Maximum call stack size exceeded

I understand the problem, and I've tried to wrapping the line which calls itself with setTimeout. This works, but, even if I set the time to 1ms, the sorting is significantly slower than if the setTimeout didn't exist.

Here's the function:

var pieces = [........]; // jumbled array

bubbleSort(0);

function bubbleSort(a) {
    if (a < bars-1) {
        onBar = a;
    } else {
        onBar = 0;
    }

    if (pieces[onBar] < pieces[onBar + 1]) {
        // Correct order

        bubbleSort(onBar + 1);

    } else {
        // Incorrect order
        var p1 = pieces[onBar];
        var p2 = pieces[onBar + 1];
        pieces[onBar] = p2;
        pieces[onBar + 1] = p1;

        bubbleSort(onBar + 1);
    }
}

For some strange reason, if I wrap one of the call lines in a setTimeout and leave the other untouched the function runs without any errors, but as soon as I leave both unwrapped it returns an error.

Thanks for your time. Any help appreciated.

1
You always call bubbleSort, not matter where you're at. So your function never ends - blex

1 Answers

0
votes

You need a branch where you return without ever calling bubbleSort.