⬅ Previous Topic
Hashing TechniqueNext Topic ⮕
Bubble Sort⬅ Previous Topic
Hashing TechniqueNext Topic ⮕
Bubble SortTopic Contents
The Heap Technique is a method of organizing elements in a binary tree structure where the parent node always maintains a relationship with its children based on either:
Heaps are typically implemented as arrays and are ideal for scenarios requiring repeated access to the largest or smallest element.
// Insert value into heap and bubble it up
function insert(heap, value):
heap.append(value)
index = heap.length - 1
while index > 0:
parent = floor((index - 1) / 2)
if heap[parent] < heap[index]: // Max Heap
swap(heap[parent], heap[index])
index = parent
else:
break
// Heapify subtree rooted at index 'i' for Max Heap
function heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
swap(arr[i], arr[largest])
heapify(arr, n, largest)
function buildMaxHeap(arr):
n = arr.length
for i from floor(n/2) - 1 down to 0:
heapify(arr, n, i)
Problem: Given an array, return the K largest elements in sorted order.
Solution: Use a Min Heap of size K. Iterate through the array, and:
function kLargestElements(arr, K):
minHeap = new MinHeap()
for num in arr:
if minHeap.size() < K:
minHeap.insert(num)
else if num > minHeap.peek():
minHeap.pop()
minHeap.insert(num)
return minHeap.toSortedArray()
The Heap Technique is vital in DSA for building efficient solutions to problems that require order-based access. Whether you're sorting, managing priorities, or scheduling, heaps offer a structured and performant approach to maintaining maximum or minimum values dynamically.
⬅ Previous Topic
Hashing TechniqueNext Topic ⮕
Bubble SortYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.