File tree Expand file tree Collapse file tree 1 file changed +18
-63
lines changed Expand file tree Collapse file tree 1 file changed +18
-63
lines changed Original file line number Diff line number Diff line change 1
-
2
- // Selection Sort
3
- function selectionSort ( arr ) {
4
-
5
- let n = arr . length ;
6
-
7
- for ( let i = 0 ; i < n - 1 ; i ++ ) {
8
-
9
- let minIndex = i ;
10
- for ( let j = i + 1 ; j < n ; j ++ ) {
11
- if ( arr [ j ] < arr [ minIndex ] ) {
12
- minIndex = j ;
1
+ let selectionSort = {
2
+ sort : ( input , animation ) => {
3
+ let j = 0
4
+ for ( let i = 0 ; i < input . length ; i ++ ) {
5
+ j = i
6
+ let minIndex = j
7
+ let min = input [ j ]
8
+ while ( j < input . length ) {
9
+ if ( input [ j ] < min ) {
10
+ min = input [ j ]
11
+ minIndex = j
12
+ }
13
+ j ++
13
14
}
15
+ if ( i !== minIndex ) animation . push ( { indices :[ i , minIndex ] , sorted : false } )
16
+ min = input [ minIndex ]
17
+ input [ minIndex ] = input [ i ]
18
+ input [ i ] = min
14
19
}
15
-
16
- if ( minIndex !== i ) {
17
- let temp = arr [ i ] ;
18
- arr [ i ] = arr [ minIndex ] ;
19
- arr [ minIndex ] = temp ;
20
- }
21
- }
22
-
23
- return arr ;
24
- }
25
-
26
- // Modified selection sort to place each iteration and details within a JavaScript object
27
- function captureSelectionSort ( arr ) {
28
-
29
- let n = arr . length ;
30
- let iterArr = [ ] ;
31
- let numIterations = 0 ;
32
- let numSwaps = 0 ;
33
- let numComparisons = 0 ;
34
-
35
- for ( let i = 0 ; i < n - 1 ; i ++ ) {
36
- numIterations ++ ;
37
- numComparisons = 0 ;
38
- numSwaps = 0 ;
39
-
40
- let minIndex = i ;
41
- for ( let j = i + 1 ; j < n ; j ++ ) {
42
- numComparisons ++ ;
43
- if ( arr [ j ] < arr [ minIndex ] ) {
44
- minIndex = j ;
45
- }
46
- }
47
-
48
- if ( minIndex !== i ) {
49
- let temp = arr [ i ] ;
50
- arr [ i ] = arr [ minIndex ] ;
51
- arr [ minIndex ] = temp ;
52
- numSwaps ++ ;
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 ) ;
20
+ return input
62
21
}
63
-
64
- return iterArr ;
65
22
}
66
-
67
- export { selectionSort , captureSelectionSort } ;
You can’t perform that action at this time.
0 commit comments