-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.cs
More file actions
45 lines (39 loc) · 1 KB
/
Copy pathMaxHeap.cs
File metadata and controls
45 lines (39 loc) · 1 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
using System;
using System.Collections.Generic;
namespace CodingProblems
{
public class MaxHeap<T> where T : IComparable
{
private List<T> Elements { get; set; }
public int Length
{
get
{
return Elements.Count;
}
}
public MaxHeap()
{
Elements = new List<T>();
}
public void Add(T value)
{
Elements.Add(value);
Heapify();
}
public void Heapify()
{
for (var i = Elements.Count - 1; i > 0; i++)
{
var parentNode = (i + 1) / 2 - 1;
parentNode = parentNode >= 0 ? parentNode : 0;
if (Elements[i].CompareTo(Elements[parentNode]) > 0)
{
var tmp = Elements[i];
Elements[i] = Elements[parentNode];
Elements[parentNode] = Elements[i];
}
}
}
}
}