Created
July 19, 2021 08:40
-
-
Save zergon321/c7e5ed02c9b26e0606485b88207d7cfa to your computer and use it in GitHub Desktop.
Heap sort in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func swap(a, b *int) { | |
t := *a | |
*a = *b | |
*b = t | |
} | |
func heapify(arr []int, i int) { | |
n := len(arr) | |
largest := i | |
l := 2*i + 1 | |
r := 2*i + 2 | |
if l < n && arr[l] > arr[largest] { | |
largest = l | |
} | |
if r < n && arr[r] > arr[largest] { | |
largest = r | |
} | |
if largest != i { | |
swap(&arr[i], &arr[largest]) | |
heapify(arr, largest) | |
} | |
} | |
func heapSort(arr []int) { | |
n := len(arr) | |
for i := n/2 - 1; i >= 0; i-- { | |
heapify(arr, i) | |
} | |
for i := n - 1; i > 0; i-- { | |
swap(&arr[0], &arr[i]) | |
heapify(arr[:i], 0) | |
} | |
} | |
func main() { | |
arr := []int{1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} | |
heapSort(arr) | |
fmt.Println(arr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment