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

javascript bubble-sort

48 просмотра

1 ответ

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;
  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){
  } else if(reRun === false){
    return array;


console.log(bubbleSort([2, 1, 3])); // yields [1, 2, 3]
Автор: Atlante Avila Источник Размещён: 08.11.2019 11:26

Ответы (1)

2 плюса


You have to patch this line:



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.

Автор: Tim Lamballais Размещён: 20.08.2016 02:42
Вопросы из категории :