github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/heap.go (about)

     1  package sort
     2  
     3  /*
     4  1.since the tree satisfies Max-Heap property, then the largest item is stored at
     5  the root node.
     6  2.swap: remove the root element and put at the end of the array (nth position)
     7  Put the last item of the tree (heap) at the vacant place.
     8  3.remove: reduce the size of the heap by 1
     9  4.heapify: heapify the root element again so that we have the highest element at root
    10  5.the process is repeated until all the items of the list are sorted.
    11  */
    12  
    13  func heapify(arr []int, n int, i int) {
    14  	// find largest among root, left child and right child
    15  	// such as index 0, its left child index is 1 and right child index is 2
    16  	largest := i
    17  	l := 2*i + 1
    18  	r := 2 * (i + 1)
    19  
    20  	if l < n && arr[l] > arr[largest] {
    21  		largest = l
    22  	}
    23  
    24  	if r < n && arr[r] > arr[largest] {
    25  		largest = r
    26  	}
    27  
    28  	if largest != i {
    29  		arr[i], arr[largest] = arr[largest], arr[i]
    30  
    31  		heapify(arr, n, largest)
    32  	}
    33  }
    34  
    35  /*
    36  总是从第一层非叶子节点开始遍历
    37  */
    38  func HeapSort(arr []int) {
    39  	n := len(arr)
    40  	// build max heap
    41  	// to build a max-heap from any tree, we can thus start heapifying each sub-tree
    42  	// from the bottom up and end up with a max-heap after the function is applied to
    43  	// all the elements including the root element.
    44  	// in the case of a complete tree. the first index of a non-leaf node is given by
    45  	// n / 2 - 1.
    46  	// all other nodes after that are leaf-nodes and thus don't need to be heapified.
    47  	for i := n/2 - 1; i >= 0; i-- {
    48  		heapify(arr, n, i)
    49  	}
    50  
    51  	for i := n - 1; i >= 0; i-- {
    52  		arr[0], arr[i] = arr[i], arr[0]
    53  
    54  		// heapify root element
    55  		heapify(arr, i, 0)
    56  	}
    57  }