1
1
/*Bubble Sort is a algorithm to sort an array. It
2
2
* 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.
3
5
*/
4
6
function bubbleSort ( items ) {
5
7
var length = items . length ;
@@ -21,7 +23,44 @@ function bubbleSort(items) {
21
23
22
24
var ar = [ 5 , 6 , 7 , 8 , 1 , 2 , 12 , 14 ] ;
23
25
//Array before Sort
26
+ console . log ( "-----before sorting-----" )
24
27
console . log ( ar ) ;
25
28
bubbleSort ( ar ) ;
26
29
//Array after sort
30
+ console . log ( "-----after sorting-----" )
27
31
console . 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