Created
April 4, 2020 22:51
-
-
Save rbtr/e3667b9c06697959461ed39db6298cd0 to your computer and use it in GitHub Desktop.
go string heap example
This file contains 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" | |
"container/heap" | |
) | |
type StringHeap []string | |
func (h StringHeap) Len() int { return len(h) } | |
func (h StringHeap) Less(i, j int) bool { return len(h[i]) > len(h[j]) } | |
func (h StringHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } | |
func (h *StringHeap) Push(x interface{}) { | |
*h = append(*h, x.(string)) | |
} | |
func (h *StringHeap) Pop() interface{} { | |
old := *h | |
n := len(old) | |
x := old[n-1] | |
*h = old[0 : n-1] | |
return x | |
} | |
func main() { | |
h := &StringHeap{"a", "ccc", "bb"} | |
heap.Init(h) | |
heap.Push(h, "dddd") | |
fmt.Printf("minimum: %s\n", (*h)[0]) | |
for h.Len() > 0 { | |
fmt.Printf("%s\n", heap.Pop(h)) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment