728x90
반응형
우선순위가 높은 데이터 순서로 자료를 삭제하는 자료구조
-> 가치가 높은 물건부터 꺼내서 확인하는 등
힙
-> 우선순위 큐를 구현하기 위해 사용하는 자료구조 중 하나
최소힙, 최대힙으로 분류
다익스트라 최단 경로 알고리즘 등 다양한 알고리즘에 사용됨
import heapq
### 최소 힙
def heapsort(iterable):
h = []
result = []
for value in iterable:
heapq.heappush(j, value)
for i in range(len(h)):
result.append(heapq.heappop(h))
return result
result = heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print(result)
### 최대 힙
def heapsort(iterable):
h = []
result = []
for value in iterable:
heapq.heappush(j, -value)
for i in range(len(h)):
result.append(-heapq.heappop(h))
return result
result = heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print(result)
반응형
'자료구조_알고리즘' 카테고리의 다른 글
자료구조) 자료구조 (0) | 2022.03.18 |
---|---|
코딩테스트 연습) [1차] 뉴스 클러스터링 (0) | 2021.06.15 |
알고리즘) 최단 경로 알고리즘 (0) | 2021.06.08 |
알고리즘) 다이나믹 프로그래밍 (0) | 2021.06.08 |
알고리즘) 이진 탐색 알고리즘 (0) | 2021.06.06 |
댓글