Skip to content

Instantly share code, notes, and snippets.

@nidhi-ag
Last active July 16, 2019 15:18
Show Gist options
  • Save nidhi-ag/ca5c95254160ec8f4c22f62527be7bcf to your computer and use it in GitHub Desktop.
Save nidhi-ag/ca5c95254160ec8f4c22f62527be7bcf to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"encoding/json"
)
func maxHeap (input []int) {
l := len(input)
for i := l/2 - 1; i>=0; i-- {
heapify(input, i, l)
}
}
func heapify (input []int, i int, n int) {
largest := i
l := 2 * i + 1
r := 2 * i + 2
if l < n && input[l] > input[i] {
largest = l
}
if r < n && input[r] > input[largest] {
largest = r
}
if i != largest {
// swap them
temp := input[largest]
input[largest] = input[i]
input[i] = temp
// heapify the changed child tree
heapify(input, largest, n)
}
}
func main() {
input := []int{0, 4, 10, 3 ,5, 1, 3, 11, 6, 12, 7}
maxHeap(input)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment