@@ -21,6 +21,7 @@ export class SortingAlgorithms {
2121 [ SortName . ShellSort ] : this . shellSort ,
2222 [ SortName . BitonicSort ] : this . bitonicSort ,
2323 [ SortName . BullySort ] : this . bullySort ,
24+ [ SortName . AverageSort ] : this . averageSort ,
2425 // 'Bully Sort 2': this.bullySort2,
2526 } ;
2627
@@ -32,6 +33,12 @@ export class SortingAlgorithms {
3233 operator : Operator ,
3334 j : number ,
3435 ) => Promise < boolean > ,
36+ private valueCompare : (
37+ arr : SortValue [ ] ,
38+ i : number ,
39+ operator : Operator ,
40+ value : number ,
41+ ) => Promise < boolean > ,
3542 private drawAndSwap : (
3643 arr : SortValue [ ] ,
3744 i : number ,
@@ -533,4 +540,36 @@ public async mergeSort(arr, start, end){
533540 }
534541 }
535542 }
543+
544+ public async averageSort ( arr : SortValue [ ] ) {
545+ await this . _averageSort ( arr , 0 , this . _columnNbr ) ;
546+ }
547+
548+ public async _averageSort ( arr : SortValue [ ] , start : number , end : number ) {
549+ if ( end - start <= 1 ) return ;
550+
551+ let sum = 0 ;
552+ for ( let i = start ; i < end ; i ++ ) {
553+ // for highlighting and counting comparison
554+ // TODO: replace
555+ await this . valueCompare ( arr , i , '>' , 0 ) ;
556+ sum += arr [ i ] . value ;
557+ }
558+ const avg = sum / ( end - start ) ;
559+ const mid = Math . floor ( ( start + end ) / 2 ) ;
560+
561+ let j = start ;
562+ for ( let i = mid ; i < end ; i ++ ) {
563+ while ( await this . valueCompare ( arr , j , '<' , avg ) ) {
564+ j ++ ;
565+ }
566+ if ( await this . valueCompare ( arr , i , '<' , avg ) ) {
567+ await this . drawAndSwap ( arr , i , j ) ;
568+ j ++ ;
569+ }
570+ }
571+
572+ await this . _averageSort ( arr , start , mid ) ;
573+ await this . _averageSort ( arr , mid , end ) ;
574+ }
536575}
0 commit comments