File tree Expand file tree Collapse file tree 1 file changed +15
-63
lines changed Expand file tree Collapse file tree 1 file changed +15
-63
lines changed Original file line number Diff line number Diff line change 1
-
2
- // Bubble Sort
3
- function bubbleSort ( arr ) {
4
-
5
- let n = arr . length ;
6
- let flag = true ;
7
- let temp ;
8
-
9
- console . log ( `n = ${ n } ` ) ;
10
-
11
- console . log ( `flag = ${ flag } ` ) ;
12
-
13
- while ( flag ) {
14
- flag = false ;
15
- for ( let i = 0 ; i < n - 1 ; i ++ ) {
16
- if ( arr [ i ] > arr [ i + 1 ] ) {
17
- temp = arr [ i ] ;
18
- arr [ i ] = arr [ i + 1 ] ;
19
- arr [ i + 1 ] = temp ;
20
- flag = true ;
1
+ let bubbleSort = {
2
+ sort : ( input , animation ) => {
3
+ let sorted = false
4
+ while ( ! sorted ) {
5
+ sorted = true
6
+ for ( let i = 0 ; i < input . length - 1 ; i ++ ) {
7
+ if ( input [ i ] > input [ i + 1 ] ) {
8
+ animation . push ( { indices :[ i , i + 1 ] , sorted :false } )
9
+ let temp = input [ i ]
10
+ input [ i ] = input [ i + 1 ]
11
+ input [ i + 1 ] = temp
12
+ sorted = false
13
+ } else {
14
+ animation . push ( { indices :[ i , i + 1 ] , sorted :true } )
15
+ }
21
16
}
22
17
}
23
18
}
24
-
25
- return arr ;
26
19
}
27
-
28
- // Modified bubble sort to place each iteration and details within a JavaScript object
29
- function captureBubbleSort ( arr ) {
30
-
31
- let n = arr . length ;
32
- let flag = true ;
33
- let temp ;
34
- let iterArr = [ ] ;
35
- let numIterations = 0 ;
36
- let numSwaps = 0 ;
37
- let numComparisons = 0 ;
38
-
39
- while ( flag ) {
40
- numIterations ++ ;
41
- numComparisons = 0 ;
42
- numSwaps = 0 ;
43
- flag = false ;
44
- for ( let i = 0 ; i < n - 1 ; i ++ ) {
45
- numComparisons ++ ;
46
- if ( arr [ i ] > arr [ i + 1 ] ) {
47
- temp = arr [ i ] ;
48
- arr [ i ] = arr [ i + 1 ] ;
49
- arr [ i + 1 ] = temp ;
50
- flag = true ;
51
- numSwaps ++ ;
52
- }
53
- }
54
-
55
- // Push copy of current array to iterations array object
56
- const iterArrObj = { } ;
57
- iterArrObj . iteration = numIterations ;
58
- iterArrObj . comparisons = numComparisons ;
59
- iterArrObj . swaps = numSwaps ;
60
- iterArrObj . array = [ ...arr ] ;
61
- iterArr . push ( iterArrObj ) ;
62
- }
63
-
64
- return iterArr ;
65
- }
66
-
67
- export { bubbleSort , captureBubbleSort } ;
You can’t perform that action at this time.
0 commit comments