@@ -22,6 +22,7 @@ export class SortingAlgorithms {
2222 [ SortName . BitonicSort ] : this . bitonicSort ,
2323 [ SortName . BullySort ] : this . bullySort ,
2424 [ SortName . AverageSort ] : this . averageSort ,
25+ [ SortName . Heapsort ] : this . heapsort ,
2526 // 'Bully Sort 2': this.bullySort2,
2627 } ;
2728
@@ -572,4 +573,66 @@ public async mergeSort(arr, start, end){
572573 await this . _averageSort ( arr , start , mid ) ;
573574 await this . _averageSort ( arr , mid , end ) ;
574575 }
576+
577+ public async heapsort ( arr : SortValue [ ] , options : AlgorithmOptions ) {
578+ switch ( options . heapType ) {
579+ case 'min' :
580+ return await this . minHeapsort ( arr ) ;
581+ case 'max' :
582+ return await this . maxHeapsort ( arr ) ;
583+ }
584+ }
585+
586+ private async minHeapsort ( arr : SortValue [ ] ) {
587+ for ( let i = Math . ceil ( arr . length / 2 ) + 1 ; i < arr . length ; i ++ ) {
588+ await this . minHeapify ( arr , 0 , i ) ;
589+ }
590+ for ( let i = 0 ; i < arr . length ; i ++ ) {
591+ await this . drawAndSwap ( arr , arr . length - 1 , i ) ;
592+ await this . minHeapify ( arr , i , arr . length - 1 ) ;
593+ }
594+ }
595+
596+ private async maxHeapsort ( arr : SortValue [ ] ) {
597+ for ( let i = Math . floor ( arr . length / 2 ) - 1 ; i >= 0 ; i -- ) {
598+ await this . maxHeapify ( arr , arr . length , i ) ;
599+ }
600+ for ( let i = arr . length - 1 ; i > 0 ; i -- ) {
601+ await this . drawAndSwap ( arr , 0 , i ) ;
602+ await this . maxHeapify ( arr , i , 0 ) ;
603+ }
604+ }
605+
606+ // This a reversed heap, with the smallest element at the last index
607+ private async minHeapify ( arr : SortValue [ ] , n : number , i : number ) {
608+ let smallestIndex = i ;
609+ const left = arr . length - 1 - ( 2 * ( arr . length - 1 - i ) + 2 ) ;
610+ const right = arr . length - 1 - ( 2 * ( arr . length - 1 - i ) + 1 ) ;
611+ if ( left > n && ( await this . compare ( arr , smallestIndex , '>' , left ) ) ) {
612+ smallestIndex = left ;
613+ }
614+ if ( right > n && ( await this . compare ( arr , smallestIndex , '>' , right ) ) ) {
615+ smallestIndex = right ;
616+ }
617+ if ( smallestIndex !== i ) {
618+ await this . drawAndSwap ( arr , i , smallestIndex ) ;
619+ await this . minHeapify ( arr , n , smallestIndex ) ;
620+ }
621+ }
622+
623+ private async maxHeapify ( arr : SortValue [ ] , n : number , i : number ) {
624+ let largestIndex = i ;
625+ const left = 2 * i + 1 ;
626+ const right = 2 * i + 2 ;
627+ if ( left < n && ( await this . compare ( arr , left , '>' , largestIndex ) ) ) {
628+ largestIndex = left ;
629+ }
630+ if ( right < n && ( await this . compare ( arr , right , '>' , largestIndex ) ) ) {
631+ largestIndex = right ;
632+ }
633+ if ( largestIndex !== i ) {
634+ await this . drawAndSwap ( arr , i , largestIndex ) ;
635+ await this . maxHeapify ( arr , n , largestIndex ) ;
636+ }
637+ }
575638}
0 commit comments