+ 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; } } } }

24th Oct 2020, 11:08 AM
Portious Banda
Portious Banda - avatar
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..
25th Oct 2020, 4:17 PM
Jayakrishna 🇮🇳
0
What is the problem you getting with this code?
24th Oct 2020, 5:58 PM
Jayakrishna 🇮🇳
0
I want to have the same program but as recursive function
25th Oct 2020, 9:43 AM
Portious Banda
Portious Banda - avatar
0
Thanks
26th Oct 2020, 9:25 AM
Portious Banda
Portious Banda - avatar