Sort an array using Bubble Sort without using loops | Function to implement bubble sort without using loops ; Base Case : If array contains a single element ; Base Case : If array contains two elements ; Store the first two elements of the list in variables a and b ; Store remaining elements in the list bs ; Store the list after each recursive call ; If a < b ; Otherwise , if b >= a ; Recursively call for the list less than the last element and and return the newly formed list ; Driver Code ; Print the array
function bubble_sort ( ar ) { if ( ar . length <= 1 ) return ar ; if ( ar . length == 2 ) { if ( ar [ 0 ] < ar [ 1 ] ) return ar ; else return [ ar [ 1 ] , ar [ 0 ] ] ; } let a = ar [ 0 ] ; let b = ar [ 1 ] ; let bs = [ ] ; for ( let i = 2 ; i < ar . length ; i ++ ) bs . push ( ar [ i ] ) ; let res = [ ] ; if ( a < b ) { let temp1 = [ ] ; temp1 . push ( b ) ; for ( let i = 0 ; i < bs . length ; i ++ ) temp1 . push ( bs [ i ] ) ; let v = bubble_sort ( temp1 ) ; v . unshift ( a ) ; res = v ; } else { let temp1 = [ ] ; temp1 . push ( a ) ; for ( let i = 0 ; i < bs . length ; i ++ ) temp1 . push ( bs [ i ] ) ; let v = bubble_sort ( temp1 ) ; v . unshift ( b ) ; res = v ; } let pass = [ ] ; for ( let i = 0 ; i < res . length - 1 ; i ++ ) pass . push ( res [ i ] ) ; let ans = bubble_sort ( pass ) ; ans . push ( res [ res . length - 1 ] ) ; return ans ; } let arr = [ 1 , 3 , 4 , 5 , 6 , 2 ] ; let res = bubble_sort ( arr ) ; document . write ( res . join ( " " ) ) ;