Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive SUM function javascript

I have been given the function below in pseudocode and I am trying to translate it to JS, but I keep getting an infinity loop.


Update

Thanks zord, mid fixed the recursion issue. Now I get the wrong sum, any suggestions?

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function SUM(arr, left, right){
  
    if(left > right){ 
        return 0 
    }
    else if(left == right){
      return arr[left]
    }

    mid = Math.floor((left + right) / 2);

    lsum = SUM(arr,left,mid);
    rsum = SUM(arr,mid+1,right); 

    return lsum + rsum

}

arr = [1,2,3,4,5]
left = 0;
right = arr.length - 1;


console.log(SUM(arr, left, right));

Thanks!

>Solution :

mid should be halfway between left and right:

mid = Math.floor((left + right) / 2);

Also, you need to make your variables block scoped as VLAZ mentioned. Otherwise they will be global, and overwritten by different runs of the function.

const mid = Math.floor((left + right) / 2);

const lsum = SUM(arr, left, mid);
const rsum = SUM(arr, mid + 1, right); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading