Repository navigation
Expand file tree
/
Copy pathMinHeap.cs
More file actions
123 lines (108 loc) · 2.81 KB
/
Copy pathMinHeap.cs
File metadata and controls
123 lines (108 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using System.Collections.Generic;
namespace Code.Heap;
public class MinHeap
{
private readonly List<int> heap;
public MinHeap()
{
heap = [];
}
public List<int> GetHeap()
{
return heap;
}
/// <summary>
/// Get the index of the parent node of the element at i-th index.
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private int Parent(int i)
{
return (i - 1) / 2;
}
/// <summary>
/// Get the index of left child node of element at the i-th index.
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private int Left(int i)
{
return 2 * i + 1;
}
/// <summary>
/// Get the index of right child node of element at the i-th index.
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private int Right(int i)
{
return 2 * i + 2;
}
/// <summary>
/// Get the min value from heap, i.e. the root node.
/// </summary>
/// <returns></returns>
public int GetMin()
{
return heap[0];
}
/// <summary>
/// Extract/remove the min value from the heap.
/// <returns></returns>
public int ExtractMin()
{
if(heap.Count == 0)
{
throw new System.Exception("Heap is empty");
}
int min = heap[0];
heap[0] = heap[^1];
heap.RemoveAt(heap.Count - 1);
if(heap.Count == 0) {
return min;
}
Heapify(0);
return min;
}
/// <summary>
/// Insert an element into the heap
/// </summary>
/// <param name="num"></param>
public void Insert(int num)
{
heap.Add(num);
int i = heap.Count - 1;
while(i != 0 && heap[Parent(i)] > heap[i])
{
(heap[Parent(i)], heap[i]) = (heap[i], heap[Parent(i)]);
i = Parent(i);
}
}
/// <summary>
/// Heapify a subtree with the root at given index.
/// This method assumes that the subtress are already heapified.
/// </summary>
/// <param name="i"></param>
private void Heapify(int i)
{
int l = Left(i); // Get the index of left child
int r = Right(i); // Get the index of right child
int smallest = i; // The index of the largest element amonng i, l, r
// Find out the index of the largest element among i, l, r
if(l < heap.Count && heap[l] < heap[smallest])
{
smallest = l;
}
if(r < heap.Count && heap[r] < heap[smallest])
{
smallest = r;
}
if(smallest == i)
{
return;
}
// Swap the smallest element with the root
(heap[smallest], heap[i]) = (heap[i], heap[smallest]);
Heapify(smallest);
}
}