728x90
정의(힙 속성)
1. 형태 속성 : 완전 이진 트리여야 한다.
2. 힙 속성 : 모든 노드의 데이터는 자식 노드들의 데이터보다 크거가 같다.
heapify 알고리즘
원하는 노드를 힙 속성에 맞게 재배치 시키는 알고리즘
시간 복잡도 - 최악의 경우 leaf Node 까지 가는 것, 즉 트리의 높이만큼 연산, O(lg(n))
힙을 만드는 시간 복잡도
- O(n * log(n)) : 모든 n개의 노드들을 다 돌아야하니까
구현
def swap(tree, index_1, index_2):
"""완전 이진 트리의 노드 index_1과 노드 index_2의 위치를 바꿔준다"""
temp = tree[index_1]
tree[index_1] = tree[index_2]
tree[index_2] = temp
def heapify(tree, index, tree_size):
"""heapify 함수"""
# 왼쪽 자식 노드의 인덱스와 오른쪽 자식 노드의 인덱스를 계산
left_child_index = 2 * index
right_child_index = 2 * index + 1
largest = index # 일단 부모 노드의 값이 가장 크다고 설정
# 왼쪽 자식 노드의 값과 비교
if 0 < left_child_index < tree_size and tree[largest] < tree[left_child_index]:
largest = left_child_index
# 오른쪽 자식 노드의 값과 비교
if 0 < right_child_index < tree_size and tree[largest] < tree[right_child_index]:
largest = right_child_index
if largest != index: # 부모 노드의 값이 자식 노드의 값보다 작으면
swap(tree, index, largest) # 부모 노드와 최댓값을 가진 자식 노드의 위치를 바꿔준다
heapify(tree, largest, tree_size) # 자리가 바뀌어 자식 노드가 된 기존의 부모 노드를대상으로 또 heapify 함수를 호출한다
# 테스트 코드
tree = [None, 15, 5, 12, 14, 9, 10, 6, 2, 11, 1] # heapify하려고 하는 완전 이진 트리
heapify(tree, 2, len(tree)) # 노드 2에 heapify 호출
print(tree)
힙 정렬 - O(nlg(n))
1. 힙을 만든다.
2. root와 마지막 노드를 바꿔준다.
3. 바꾼 노드는 노드에서 제외한다.
4. 새로운 노드가 힙 속성을 지킬 수 있게 heapiy 호출
* 내림차순 : 부모 노드의 데이터가 자식 노드의 데이터보다 작다고 조건을 변경
구현
def swap(tree, index_1, index_2):
"""완전 이진 트리의 노드 index_1과 노드 index_2의 위치를 바꿔준다"""
temp = tree[index_1]
tree[index_1] = tree[index_2]
tree[index_2] = temp
def heapify(tree, index, tree_size):
"""heapify 함수"""
# 왼쪽 자식 노드의 인덱스와 오른쪽 자식 노드의 인덱스를 계산
left_child_index = 2 * index
right_child_index = 2 * index + 1
largest = index # 일단 부모 노드의 값이 가장 크다고 설정
# 왼쪽 자식 노드의 값과 비교
if 0 < left_child_index < tree_size and tree[largest] < tree[left_child_index]:
largest = left_child_index
# 오른쪽 자식 노드의 값과 비교
if 0 < right_child_index < tree_size and tree[largest] < tree[right_child_index]:
largest = right_child_index
if largest != index: # 부모 노드의 값이 자식 노드의 값보다 작으면
swap(tree, index, largest) # 부모 노드와 최댓값을 가진 자식 노드의 위치를 바꿔준다
heapify(tree, largest, tree_size) # 자리가 바뀌어 자식 노드가 된 기존의 부모 노드를대상으로 또 heapify 함수를 호출한다
def heapsort(tree):
"""힙 정렬 함수"""
tree_size = len(tree)
# 마지막 인덱스부터 처음 인덱스까지 heapify를 호출한다
for index in range(tree_size-1, 0, -1):
heapify(tree, index, tree_size)
# 마지막 인덱스부터 처음 인덱스까지
for i in range(tree_size-1, 0, -1):
swap(tree, 1, i) # root 노드와 마지막 인덱스를 바꿔준 후
heapify(tree, 1, i) # root 노드에 heapify를 호출한다
# 테스트 코드
data_to_sort = [None, 6, 1, 4, 7, 10, 3, 8, 5, 1, 5, 7, 4, 2, 1]
heapsort(data_to_sort)
print(data_to_sort)
728x90