github.com/andy2046/gopie@v0.7.0/pkg/heapsort/heapsort.go (about)

     1  // Package heapsort implements Heapsort.
     2  package heapsort
     3  
     4  // Sort sorts the slice.
     5  func Sort(data []int) {
     6  	sort(data)
     7  }
     8  
     9  func sort(a []int) {
    10  	n := len(a)
    11  	buildMaxHeap(a, n)
    12  	sortDown(a, n)
    13  }
    14  
    15  func buildMaxHeap(a []int, n int) {
    16  	for k := n / 2; k >= 1; k-- {
    17  		sink(a, k, n)
    18  	}
    19  }
    20  
    21  func sortDown(a []int, n int) {
    22  	for n > 1 {
    23  		swap(a, 1, n)
    24  		n--
    25  		sink(a, 1, n)
    26  	}
    27  }
    28  
    29  func sink(a []int, k, n int) {
    30  	for 2*k <= n {
    31  		j := 2 * k
    32  
    33  		// is right key greater than left key
    34  		if j < n && less(a, j, j+1) {
    35  			j++
    36  		}
    37  
    38  		// when both right and left child are not greater than parent
    39  		if !less(a, k, j) {
    40  			break
    41  		}
    42  
    43  		// moves the greater key up
    44  		swap(a, k, j)
    45  
    46  		k = j
    47  	}
    48  }
    49  
    50  func less(a []int, i, j int) bool {
    51  	return a[i-1] < a[j-1]
    52  }
    53  
    54  func swap(a []int, i, j int) {
    55  	a[i-1], a[j-1] = a[j-1], a[i-1]
    56  }