2025-04-17 07:21:39 +02:00

65 lines
1.7 KiB
Python

import numpy as np
import matplotlib.pyplot as plt
def fix_heap(heap, idx, highest):
# Standard heapify: ensure the subtree rooted at idx is a max heap
largest = idx
left = 2 * idx + 1
right = 2 * idx + 2
# Check if left child exists and is greater than root
if left <= highest and heap[left] > heap[largest]:
largest = left
# Check if right child exists and is greater than largest so far
if right <= highest and heap[right] > heap[largest]:
largest = right
# Swap and continue heapifying if root is not largest
if largest != idx:
heap[idx], heap[largest] = heap[largest], heap[idx]
fix_heap(heap, largest, highest)
def linearize_heap_in_order(heap):
"""
Returns a copy of the heap as a linear list using in-order traversal.
"""
heap_copy = heap.copy()
n = len(heap_copy)
result = []
def in_order_traversal(index):
if index < n:
# Traverse left subtree
in_order_traversal(2 * index + 1)
# Visit node
result.append(heap_copy[index])
# Traverse right subtree
in_order_traversal(2 * index + 2)
in_order_traversal(0)
return result
def heap_sort(A):
n = len(A)
heap = A.copy()
# Build max heap
for i in range(n // 2 - 1, -1, -1):
fix_heap(heap, i, n - 1)
# Extract elements one by one
for i in range(n - 1, 0, -1):
heap[0], heap[i] = heap[i], heap[0]
fix_heap(heap, 0, i - 1)
return heap
amount = 10
Y = np.linspace(0, 100, amount)
Y = np.random.permutation(Y)
X = np.linspace(0, 100, amount)
plt.scatter(X, Y)
Y = heap_sort(Y)
plt.scatter(X, Y)
plt.show()