Too Much Recursio (Bubble Sort / JS)

Working on implementing bubble sort. My attempted solution has a switch to check if a swap occurred and if it did, then the sort is performed on the array again. Code:

function bubbleSort(array) {
  // change code below this line
  let switchOccurred = false
  for (let i = 0; i<array.length-1; i++){
    if (array[i] > array[i+1]){
      let x = array[i+1]
      array[i+1] = array[i];
      array[i] = x
      switchOccurred = true
    }
  } if (switchOccurred = true) {
    bubbleSort(array)
  } else {
  return array;
  }
  // change code above this line
}

bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);

This generates “InternalError: too much recursion.” Can anyone explain why and how to fix that?

Thanks!

You really don’t want to do a bubble sort with recursion. I would use a while (switchOccurred).

1 Like

you have at least one issue here, this is not a comparison

then you also never do anything with the value returned from bubbleSort

1 Like