+ 1
Recursive functions
Help me with the recursive function of this iterative function below, 🙏 var ar = [23, 1000, 1, -1, 8, 3]; println(ar); bubbleSort(ar); println(ar); function bubbleSort(ar) { var shouldSort = true; while(shouldSort) { shouldSort = false; for(var i = 0; i < ar.length - 1; i++) { var a = ar[i]; if ( a > ar[i+1] ) { ar[i] = ar[i+1]; ar[i+1] = a; shouldSort = true; } } } }
4 Réponses
+ 1
You have a while loop, so it can be possible to make it recursive function like this :
var ar = [23, 1000, 1, -1, 8, 3];
console.log(JSON.stringify(ar));
bubbleSort(ar);
console.log(JSON.stringify(ar));
function bubbleSort(ar)
{
var shouldSort = false;
for(var i = 0; i < ar.length - 1; i++)
{
var a = ar[i];
if ( a > ar[i+1] )
{
ar[i] = ar[i+1];
ar[i+1] = a;
shouldSort = true;
}
if(shouldSort)
bubbleSort(ar);
}
}
Edit : it can be reduced the number of iteration.. Hope you can work on it later..
0
What is the problem you getting with this code?
0
I want to have the same program but as recursive function
0
Thanks