@@ -66,6 +66,33 @@ export function initVisualisers() {
66
66
// Define helper functions
67
67
// -------------------------------------------------------------------------------
68
68
69
+ // This function highlights all the runs alternating colours, kudos to chatgpt
70
+ function highlightNaturalRuns ( vis , array , runAColor , runBColor ) {
71
+ let toggle = 0 ; // 0 = runAColor, 1 = runBColor
72
+ let i = 0 ;
73
+
74
+ while ( i < array . length ) {
75
+ let start = i ;
76
+
77
+ // Find the length of the increasing run
78
+ while ( i < array . length - 1 && array [ i ] <= array [ i + 1 ] ) {
79
+ i ++ ;
80
+ }
81
+
82
+ // Highlight the run
83
+ for ( let j = start ; j <= i ; j ++ ) {
84
+ highlight ( vis , j , toggle == 0 ? runAColor : runBColor ) ;
85
+ }
86
+
87
+ // Flip toggle between 0 and 1 for the next run
88
+ toggle = 1 - toggle ;
89
+
90
+ // Move to the next element after the current run
91
+ i ++ ;
92
+ }
93
+ }
94
+
95
+
69
96
70
97
71
98
/**
@@ -106,18 +133,20 @@ export function run_msort() {
106
133
107
134
do {
108
135
109
- chunker . add ( 'MainWhile' , ( ) => {
136
+ chunker . add ( 'MainWhile' , ( vis , a ) => {
110
137
// no animation
111
- } , [ ] ) ;
138
+ highlightNaturalRuns ( vis , a , runAColor , runBColor ) ;
139
+ } , [ A ] ) ;
112
140
113
141
114
142
115
143
runcount = 0 ;
116
144
let left = 0 ;
117
145
118
- chunker . add ( 'runcount' , ( vis , c_rcount ) => {
146
+ chunker . add ( 'runcount' , ( vis , a , c_rcount ) => {
147
+ vis . array . set ( a , 'msort_arr_nat' ) ;
119
148
set_simple_stack ( vis . array , [ c_rcount ] ) ;
120
- } , [ runcount ] ) ;
149
+ } , [ A , runcount ] ) ;
121
150
122
151
chunker . add ( 'left' , ( vis , c_left ) => {
123
152
assignVarToA ( vis , 'left' , c_left , size ) ;
@@ -340,13 +369,21 @@ export function run_msort() {
340
369
} , [ A , left , runcount ] ) ;
341
370
342
371
} while ( left < size ) ;
372
+
373
+ chunker . add ( 'mergeDone' , ( vis , a ) => {
374
+ highlightNaturalRuns ( vis , a , runAColor , runBColor ) ;
375
+ } , [ A ] )
376
+
343
377
} while ( runcount > 1 ) ;
344
378
345
- chunker . add ( 'Done' , ( vis ) => {
346
- for ( let i = 0 ; i < size ; i ++ ) highlight ( vis , i , "sortColor" ) ;
347
- assignVarToA ( vis , 'Done' , size , size ) ;
379
+ chunker . add ( 'Done' , ( vis , a ) => {
380
+ vis . array . set ( a , 'msort_arr_nat' ) ;
381
+ for ( let i = 0 ; i < size ; i ++ ) {
382
+ highlight ( vis , i , sortColor ) ;
383
+ }
384
+
348
385
set_simple_stack ( vis . array , [ "DONE" ] ) ;
349
- } , [ ] ) ;
386
+ } , [ A ] ) ;
350
387
351
388
const maxValue = entire_num_array . reduce ( ( acc , curr ) => ( acc < curr ? curr : acc ) , 0 ) ;
352
389
0 commit comments