Search code examples
javascriptbubble-sort

Why is my bubble sort function skipping over the else if and returns undefined?


I have a function for bubble sort that I felt was going to work for sure. I just don't understand why the function simply returns undefined. I have it checking whether it should reRun or not. If my reRun variable is set to true, then it should recurse and if it's set to false it should return the array.

Here's my code:

var bubbleSort = function(array) {
  // Your code here.
  var tmp;
  var next;
  var curr;
  var reRun = false;
  console.log(reRun)
  for(i = 0; i < array.length; i++){
    // set curr var to current item and tmp to the next one
    next = array[i+1];
    // console.log('next', next)
    curr = array[i];
    // console.log('curr', curr)
    // check to see if the curr value is greater than the nex
    if(curr > next){
      // if it is greater than set temp to be the next val and swap
      // the two positions
      array[i] = next
      array[i+1] = curr;
      reRun = true;
    }
  }
  if(reRun === true){
    bubbleSort(array)
  } else if(reRun === false){
    return array;
  }

};

console.log(bubbleSort([2, 1, 3])); // yields [1, 2, 3]

Solution

  • You have to patch this line:

    bubbleSort(array);
    

    to:

    return bubbleSort(array);
    

    The reason for this is that the result is only returned by the final call to bubbleSort, which is then never propagated up the stack through all the previous calls, since you're not returning anything from those.