1

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.

Caspar B
  • 499
  • 1
  • 6
  • 19
  • 6
    You always call `bubbleSort`, not matter where you're at. So your function never ends – blex Oct 23 '17 at 22:18
  • [`setTImeout` is NOT a solution to the stack overflow problem](https://stackoverflow.com/a/43596323/633183) – Mulan Oct 24 '17 at 01:57

1 Answers1

0

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

meza
  • 8,247
  • 1
  • 14
  • 23
  • Could you explain? I don't understand where I'd implement this. – Caspar B Oct 23 '17 at 23:11
  • Right now, your function doesn't know when it is "finished". In the case of being the correct order, it moves on to the next one. In case it's the incorrect order, it moves on to the next one. When should it stop? – meza Oct 23 '17 at 23:12
  • Right. I understand. Thanks – Caspar B Oct 23 '17 at 23:18