11/*Bubble Sort is a algorithm to sort an array. It
22* compares adjacent element and swaps thier position
3+ * The big O on bubble sort in worst and best case is O(N^2).
4+ * Not efficient.
35*/
46function bubbleSort ( items ) {
57 var length = items . length ;
@@ -21,7 +23,44 @@ function bubbleSort(items) {
2123
2224var ar = [ 5 , 6 , 7 , 8 , 1 , 2 , 12 , 14 ] ;
2325//Array before Sort
26+ console . log ( "-----before sorting-----" )
2427console . log ( ar ) ;
2528bubbleSort ( ar ) ;
2629//Array after sort
30+ console . log ( "-----after sorting-----" )
2731console . log ( ar ) ;
32+
33+ /*alternative implementation of bubble sort algorithm.
34+ Using a while loop instead. For educational purposses only
35+ */
36+ /*
37+ *In bubble sort, we keep iterating while something was swapped in
38+ *the previous inner-loop iteration. By swapped I mean, in the
39+ *inner loop iteration, we check each number if the number proceeding
40+ *it is greater than itself, if so we swap them.
41+ */
42+
43+ function bubbleSort ( arr ) {
44+ var swapped = true ;
45+ while ( swapped ) {
46+ var swapped = false ;
47+ for ( var i = 0 ; i < arr . length ; i ++ ) {
48+ if ( arr [ i ] > arr [ i + 1 ] ) {
49+ var temp = arr [ i ] ;
50+ arr [ i ] = arr [ i + 1 ] ;
51+ arr [ i + 1 ] = temp ;
52+ swapped = true ;
53+ }
54+ }
55+ }
56+ return arr ;
57+ }
58+
59+ //test
60+ console . log ( "-----before sorting-----" )
61+ var array = [ 10 , 5 , 3 , 8 , 2 , 6 , 4 , 7 , 9 , 1 ] ;
62+ console . log ( array ) ;
63+ console . log ( "-----after sorting-----" )
64+ console . log ( bubbleSort ( array ) ) ;
65+
66+
0 commit comments