PHpullh
학습 라이브러리/Go/힙 (container/heap)

GO · 컬렉션

힙 (container/heap)

container/heap으로 우선순위 큐를 구현합니다. heap.Interface를 구현해야 합니다.

컬렉션고급heappriority-queuecontainerdata-structure

핵심 설명

container/heap으로 우선순위 큐를 구현합니다. heap.Interface를 구현해야 합니다.

Go code

package main

import (
	"container/heap"
	"fmt"
)

type Item struct {
	Value    string
	Priority int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int            { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool   { return pq[i].Priority > pq[j].Priority }
func (pq PriorityQueue) Swap(i, j int)        { pq[i], pq[j] = pq[j], pq[i] }

func (pq *PriorityQueue) Push(x any) {
	*pq = append(*pq, x.(*Item))
}

func (pq *PriorityQueue) Pop() any {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[:n-1]
	return item
}

func main() {
	pq := &PriorityQueue{}
	heap.Init(pq)

	heap.Push(pq, &Item{"낮음", 1})
	heap.Push(pq, &Item{"높음", 10})
	heap.Push(pq, &Item{"중간", 5})

	for pq.Len() > 0 {
		item := heap.Pop(pq).(*Item)
		fmt.Printf("[%d] %s\n", item.Priority, item.Value)
	}
}

학습 팁

Less에서 >를 사용하면 최대 힙(높은 우선순위 먼저), 를 사용하면 최소 힙이 됩니다.

주의할 점

직접 append하지 말고 반드시 heap.Push/heap.Pop을 사용해야 힙 속성이 유지됩니다.

자주 묻는 질문

힙 (container/heap)란 무엇인가요?

container/heap 으로 우선순위 큐를 구현합니다. heap.Interface 를 구현해야 합니다.

힙 (container/heap) 학습 시 주의할 점은 무엇인가요?

직접 append 하지 말고 반드시 heap.Push / heap.Pop 을 사용해야 힙 속성이 유지됩니다.