ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Binary Heap: Max Heap Implementation

Go

Goal -- WPM

Ready
Exercise Algorithm Area
1package main
2
3import (
4 "fmt"
5)
6
7// MaxHeap implements a max-heap using a slice.
8type MaxHeap []int
9
10// Len returns the number of elements in the heap.
11func (h MaxHeap) Len() int { return len(h) }
12
13// Less checks if the element at index i is less than the element at index j.
14// For a max-heap, we want the parent to be GREATER than its children.
15// So, Less(i, j) should return true if h[i] < h[j].
16func (h MaxHeap) Less(i, j int) bool { return h[i] < h[j] }
17
18// Swap swaps the elements at indices i and j.
19func (h MaxHeap) Swap(i, j int) {
20 h[i], h[j] = h[j], h[i]
21}
22
23// Push adds an element to the heap.
24func (h *MaxHeap) Push(x interface{}) {
25 // Push and Pop use pointer receivers because they modify the slice's length,
26 // not just its contents.
27 *h = append(*h, x.(int))
28}
29
30// Pop removes and returns the maximum element from the heap.
31func (h *MaxHeap) Pop() interface{} {
32 old := *h
33 n := len(old)
34 item := old[n-1]
35 *h = old[0 : n-1]
36 return item
37}
38
39// heapifyUp maintains the heap property by moving an element up the tree.
40func (h *MaxHeap) heapifyUp(index int) {
41 for index > 0 {
42 parentIndex := (index - 1) / 2
43 if !h.Less(index, parentIndex) { // If current element is NOT less than parent (i.e., >=)
44 h.Swap(index, parentIndex)
45 index = parentIndex
46 } else {
47 break // Heap property satisfied
48 }
49 }
50}
51
52// heapifyDown maintains the heap property by moving an element down the tree.
53func (h *MaxHeap) heapifyDown(index int) {
54 lastIndex := h.Len() - 1
55 for {
56 leftIndex := 2*index + 1
57 rightIndex := 2*index + 2
58 largestIndex := index
59
60 // Check if left child exists and is greater than current largest
61 if leftIndex <= lastIndex && h.Less(largestIndex, leftIndex) {
62 largestIndex = leftIndex
63 }
64
65 // Check if right child exists and is greater than current largest
66 if rightIndex <= lastIndex && h.Less(largestIndex, rightIndex) {
67 largestIndex = rightIndex
68 }
69
70 // If the largest element is not the current element, swap and continue heapifying down
71 if largestIndex != index {
72 h.Swap(index, largestIndex)
73 index = largestIndex
74 } else {
75 break // Heap property satisfied
76 }
77 }
78}
79
80// Insert adds a new element to the max heap.
81func (h *MaxHeap) Insert(value int) {
82 h.Push(value)
83 h.heapifyUp(h.Len() - 1)
84}
85
86// ExtractMax removes and returns the maximum element from the heap.
87// Returns an error if the heap is empty.
88func (h *MaxHeap) ExtractMax() (int, error) {
89 if h.Len() == 0 {
90 return 0, fmt.Errorf("heap is empty")
91 }
92 maxVal := (*h)[0]
93 lastVal := h.Pop().(int)
94
95 if h.Len() > 0 {
96 (*h)[0] = lastVal
97 h.heapifyDown(0)
98 }
99
100 return maxVal, nil
101}
102
103func main() {
104 heap := &MaxHeap{}
105
106 heap.Insert(10)
107 heap.Insert(20)
108 heap.Insert(5)
109 heap.Insert(30)
110
111 fmt.Println("Heap after insertions:", *heap)
112
113 max, err := heap.ExtractMax()
114 if err == nil {
115 fmt.Printf("Extracted max: %d\n", max)
116 }
117 fmt.Println("Heap after extraction:", *heap)
118
119 max, err = heap.ExtractMax()
120 if err == nil {
121 fmt.Printf("Extracted max: %d\n", max)
122 }
123 fmt.Println("Heap after extraction:", *heap)
124
125 // Test empty heap extraction
126 for heap.Len() > 0 {
127 heap.ExtractMax()
128 }
129 _, err = heap.ExtractMax()
130 if err != nil {
131 fmt.Println("Error extracting from empty heap:", err)
132 }
133}
Algorithm description viewbox

Binary Heap: Max Heap Implementation

Algorithm description:

This Go program implements a Max Heap data structure, which is a binary tree-based data structure that satisfies the heap property: in a max heap, for any given node C, if P is a parent node of C, then the value of P is greater than or equal to the value of C. This is crucial for efficiently retrieving the maximum element.

Algorithm explanation:

The `MaxHeap` type is implemented as a slice of integers. It satisfies the `heap.Interface` by providing `Len`, `Less`, `Swap`, `Push`, and `Pop` methods. The `Less` method is defined such that `h[i] < h[j]` returns true, making it a max heap (the largest element will bubble up). `Push` appends an element, and `Pop` removes the last element. `heapifyUp` is used after `Push` to restore the heap property by moving the new element upwards. `heapifyDown` is used after `Pop` to restore the heap property by moving the element that replaced the root downwards. `Insert` calls `Push` and `heapifyUp`, while `ExtractMax` retrieves the root, replaces it with the last element, and then calls `heapifyDown`. The time complexity for `Insert` and `ExtractMax` is O(log N), where N is the number of elements in the heap, due to the heapify operations. Space complexity is O(N) to store the heap elements.

Pseudocode:

define MaxHeap as a slice of integers

implement heap.Interface for MaxHeap:
  Len(): return length of slice
  Less(i, j): return true if element at i < element at j
  Swap(i, j): swap elements at i and j
  Push(x): append x to slice
  Pop(): remove and return last element from slice

function heapifyUp(heap, index):
  while index > 0:
    parentIndex = (index - 1) / 2
    if heap[index] > heap[parentIndex]: // Max heap property
      swap heap[index] and heap[parentIndex]
      index = parentIndex
    else:
      break

function heapifyDown(heap, index):
  lastIndex = heap.Len() - 1
  while true:
    leftIndex = 2 * index + 1
    rightIndex = 2 * index + 2
    largestIndex = index

    if leftIndex <= lastIndex and heap[leftIndex] > heap[largestIndex]:
      largestIndex = leftIndex
    if rightIndex <= lastIndex and heap[rightIndex] > heap[largestIndex]:
      largestIndex = rightIndex

    if largestIndex != index:
      swap heap[index] and heap[largestIndex]
      index = largestIndex
    else:
      break

function Insert(heap, value):
  heap.Push(value)
  heapifyUp(heap, heap.Len() - 1)

function ExtractMax(heap):
  if heap is empty:
    return error
  maxVal = heap[0]
  lastVal = heap.Pop()
  if heap is not empty:
    heap[0] = lastVal
    heapifyDown(heap, 0)
  return maxVal
end function