Skip to main content

Posts

Showing posts from July, 2019

Recursive Bubble Sort in Javascript

Recursive Bubble Sort in Javascript Bubble Sort can be carried out recursively as follows: const recursiveBubbleSort = function ( a , p = a . length - 1 ) { if ( p < 1 ) { return a ; } for ( let i = 0 ; i < p ; i ++) { if ( a [ i ] > a [ i + 1 ]) { [ a [ i ], a [ i + 1 ]] = [ a [ i + 1 ], a [ i ]]; } } return recursiveBubbleSort ( a , p - 1 ); } console . log ( recursiveBubbleSort ([ 2 , 1 , 4 , 7 , 3 , 9 , 5 , 6 , 8 ])); You can run the code here:  https://repl.it/@VinitKhandelwal/bubble-sort-recursive-javascript

Bubble Sort in Javascript

Bubble Sort in Javascript Comparing each with the neighbor and swapping if first is greater than the next Time Complexity Best: Ω(n^2) Average: θ(n^2) Worst: O(n^2) function bubbleSort ( arr ){ console . log ( "Input Array" ); console . log ( arr ); let i = 0 let temp ; let notSorted ; do { notSorted = false ; for ( let j = 0 ; j < arr . length - i ; j ++) { if ( arr [ j ] > arr [ j + 1 ]) { notSorted = true ; temp = arr [ j ]; arr [ j ] = arr [ j + 1 ]; arr [ j + 1 ] = temp ; console . log ( arr [ j ], "swapped with" , arr [ j + 1 ]) console . log ( arr ); } else { console . log ( "SKIP" ); } console . log ( j , arr . length - i ); } i ++; } while ( notSorted ) console . log ( "Sorted using Bubble Sort" ); return arr ; } // console . log ( bubbleSort ([ 1 , 2...