forked from Hydrologist/msnp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxHeap.cs
80 lines (71 loc) · 2.01 KB
/
maxHeap.cs
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
using System;
using System.Collections.Generic;
using System.Text;
namespace LiyeLib
{
//A binaryheap Data struture. Adapted from Weiss's C++ code by Liye Zhang
class Maxheap<T>
{
public int currentSize;
List<IComparable> array;
public Maxheap()
{
array = new List<IComparable>();
array.Add(null);
currentSize = 0;
}
public void insert(IComparable x)
{
if (currentSize + 1 >= array.Count) //if we are out of room
{
array.Add(x);
}
// Percolate up
int hole = ++currentSize;
for (; hole > 1 && x.CompareTo(array[hole / 2]) > 0; hole /= 2)
array[hole] = array[hole / 2];
array[hole] = x;
}
public IComparable deleteMax()
{
IComparable temp = array[1];
array[1] = array[currentSize--];
percolateDown(1);
return temp;
}
public void percolateDown(int hole)
{
/* 1*/
int child;
/* 2*/
IComparable tmp = array[hole];
/* 3*/
for (; hole * 2 <= currentSize; hole = child)
{
/* 4*/
child = hole * 2;
/* 5*/
if (child != currentSize && array[child + 1].CompareTo(array[child]) > 0)
/* 6*/
child++;
/* 7*/
if (array[child].CompareTo(tmp) > 0)
/* 8*/
array[hole] = array[child];
else
/* 9*/
break;
}
/*10*/
array[hole] = tmp;
}
public bool isEmpty()
{
return currentSize == 0;
}
public T findMax()
{
return (T)array[1];
}
}
}