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!