Here's a simple example of binary heap sorting in action:
# Initialize a list of numbers (or socks)
numbers = [4, 2, 7, 1, 3]
# Create a binary heap
def heapify(numbers):
for i in range(len(numbers)):
parent = (i - 1) // 2
if i > 0 and numbers[parent] > numbers[i]:
numbers[parent], numbers[i] = numbers[i], numbers[parent]
heap = []
for num in numbers:
heap.append(num)
heapify(heap)
# Sort the heap
def heapify(heap):
for i in range(len(heap)):
if i > 0 and heap[i] < heap[(i + 1) // 2]:
heap[i], heap[(i + 1) // 2] = heap[(i + 1) // 2], heap[i]
if i > 0 and heap[i] > heap[(i + 1) // 2]:
heap[i], heap[(i + 1) // 2] = heap[(i + 1) // 2], heap[i]
if i > 0 and heap[i] < heap[i // 2]:
heap[i], heap[i // 2] = heap[i // 2], heap[i]
if i > 0 and heap[i] > heap[i // 2]:
heap[i], heap[i // 2] = heap[i // 2], heap[i]
# Print the sorted list
sorted_numbers = []
while len(heap) > 0:
sorted_numbers.append(heap.pop())
print(sorted_numbers)
Sort your own socks with this code, but be warned: it's not as simple as it looks.
Want to see more?