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