Heapsort - read heap sequence directly

What is Heap Sort?

For a detailed explanation of heap sorting, see here, the easy-to-understand
written from
article here is a small root heap and it needs to be swapped 2with the 3position to match

Do not swap the top of the heap, read directly

According to the nature of the big root heap (the parent node is always larger than the left and right child nodes), then we can take the top one of the heap every time (similar to rebuilding the heap), then record the child nodes, and then compare the current maximum , repeat the above steps to
directly explain the code:
insert image description here

Code

language of codeTS

  testFunc(){
     
     
       let arr = [8,1,5,2,15,2,5,89,39,67,9,3,48,4,4,1,0,9,10,11,45]
       this.buildMaxHeap(arr)
       let result = this.maxSort(arr)
   }

  buildMaxHeap(arr: number[]){
     
     
       for(let i = Math.floor(arr.length / 2); i >= 0; i--){
     
     
           this.heapify(arr, i)
       }
   }
   heapify(arr: number[], index: number){
     
     
       let left = index * 2 + 1
       let right = index * 2 + 2
       let largest = index
       if(left < arr.length && arr[left] > arr[largest]){
     
     
           largest = left
       }
       if(right < arr.length && arr[right] > arr[largest]){
     
     
           largest = right
       }
       if(largest != index){
     
     
           let temp = arr[index]
           arr[index] = arr[largest]
           arr[largest] = temp
           this.heapify(arr, largest)
       }
   }
   //只有这里有差别而已,其他都没差别
   maxSort(arr: number[]){
     
     
       let maxTemp: number[] = []
       let result: number[] = []
       let curIndex = 0
       maxTemp.push(curIndex)
       while(maxTemp.length > 0){
     
     
           curIndex = maxTemp.shift()
           result.push(arr[curIndex])
           
           let left = curIndex * 2 + 1
           let right = curIndex * 2 + 2
           if(left < arr.length){
     
     
               maxTemp.push(left)
           }
           if(right < arr.length){
     
     
               maxTemp.push(right)
           }
           maxTemp.sort((a, b)=>{
     
     
               return arr[b] - arr[a]
           })
       }
       return result
   }

To sum up, just to provide an idea... The running speed is definitely not as fast as rebuilding the heap

Guess you like

Origin blog.csdn.net/u014147126/article/details/124338980