I tried to build a Bubble Sort algorithm to sort an array. It works in sorting the array, but for its recursive implementation, it never stops... I understand I should put some break clause to stop the execution of the for loop, but I'm not sure where.
Could please someone provide some useful guidance on these types of problems with recursive functions?
Thank you
input = [1, 7, 5, 6, 8, 9, 9, 100, 24, 35, 10]
function bubbleSort(input) {
for (let i = 0; i < input.length; i++) {
if (input[i] > input[i + 1]) {
let newvar = input[i];
input[i] = input[i + 1];
input[i + 1] = newvar;
bubbleSort(input);
}
}
};
console.log(bubbleSort(input));
input.length - 1so that thei + 1offsets in the loop body don't go beyond the end.forloop finds one or more swaps to make. If it makes at least one swap, then do the recursive call outside theforloop. If not, then the array is sorted and the function can exit.