JavaScript recursion: Maximum call stack size exceeded

前端 未结 4 805
醉话见心
醉话见心 2021-02-13 02:29

I have a recursive function for moving some circles on a canvas. Overed circle is enlarged (zoom in) and all the other circles is pushed away. Pushed circles push other circles

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 03:06

    Try to make sure the recursion step is only done for greater than base case. For example in quicksort here:

    function qsort(k){
    
    if(k == []){
        return k;
    }
    if(k.length == 1){
        return k;
    }
    
    //pick random pivot
    
    var p = Math.floor(Math.random()*k.length);
    console.log("pivot is" +  p + "\n");
    
    //set left and right iter
    
    var l = 0; var r = k.length - 1;
    
    while( l < r){
    console.log('hi\n');
    //move l until its element is bigger than pivot
    
    while(k[l] < k[p] && l < k.length) {
        l++;
        console.log('h1i\n');
    
    }
    
    //move r until its element is smaller than pivot
    
    while(k[r] > k[p] && r >= 0) {r--;
    
        console.log('h2i\n');
    }
    
    //swap k[l] with k[r]
    
    var temp = k[l]; k[l] = k[r]; k[r] = temp;
    }
    
    if(l == r){
    //swap k[l] with k[p]
    
    temp = k[l]; k[l] = k[p]; k[p] = temp;
    
    }
    
    
    
    var lk = k.slice(0,p); var rk = k.slice(p,k.length);
    
    console.log(lk);
    console.log(rk);
    
    if(lk.length > 1){
     lk = qsort(lk);
    }
    if(rk.length > 1){
     rk = qsort(rk);
    }
    
    result = lk.concat(rk);
    
    console.log(result);
    
    return result;
    
    }
    
    var k = [23,245,67,34,24];
    var result = qsort(k);
    console.log(result);
    //document.write(result);
    

    If instead of lk.length > 1 you used something like lk != [] or not have a check, it could sometimes give call stack size exceeded errors and sometimes work depending on which pivots got chosen.

提交回复
热议问题