post-custom-banner

Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is commonly used to efficiently maintain the minimum or maximum element in a collection, allowing for quick access to the smallest/largest item.

In the context of heaps, the term "heap" often refers to a binary heap, which is a complete binary tree where every parent node has a value smaller (in a min-heap) or larger (in a max-heap) than its child nodes. This property ensures that the minimum (or maximum) element is always at the root of the heap.

simple code in python:

#### example of HEAP from gpt ####
import heapq

# Create an empty heap
heap = []

# Insert elements into the heap
heapq.heappush(heap, 5)
heapq.heappush(heap, 2)
heapq.heappush(heap, 10)
heapq.heappush(heap, 1)

print("Heap:", heap)  # Output: [1, 2, 10, 5]

# Pop and retrieve the smallest element from the heap
smallest = heapq.heappop(heap)
print("Smallest element:", smallest)  # Output: 1
print("Updated heap:", heap)  # Output: [2, 5, 10]

# Get the n smallest elements from the heap without popping them
smallest_elements = heapq.nsmallest(2, heap)
print("Smallest 2 elements:", smallest_elements)  # Output: [2, 5]

# Convert a list into a heap in-place
list_to_heap = [8, 3, 6, 4, 2]
heapq.heapify(list_to_heap)
print("Heapified list:", list_to_heap)  # Output: [2, 3, 6, 4, 8]
profile
multi-national communicator with programming (back-end)
post-custom-banner

0개의 댓글