-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.go
More file actions
42 lines (36 loc) · 717 Bytes
/
heap_sort.go
File metadata and controls
42 lines (36 loc) · 717 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package sort
import (
"golang.org/x/exp/constraints"
)
func HeapSort[T constraints.Integer](arr []T) {
n := len(arr)
buildMaxHeap(arr)
for i := n - 1; i > 0; i-- {
arr[0], arr[i] = arr[i], arr[0]
maxHeapify(arr, 0, i)
}
}
func buildMaxHeap[T constraints.Integer](arr []T) {
n := len(arr)
for i := n/2 - 1; i >= 0; i-- {
maxHeapify(arr, i, n)
}
}
func maxHeapify[T constraints.Integer](arr []T, i, n int) {
largest := i
for {
left := 2*i + 1
right := 2*i + 2
if left < n && arr[largest] < arr[left] {
largest = left
}
if right < n && arr[largest] < arr[right] {
largest = right
}
if largest == i {
break
}
arr[i], arr[largest] = arr[largest], arr[i]
i = largest
}
}