-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.java
128 lines (106 loc) · 3.44 KB
/
Heap.java
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
124
125
126
127
128
//Heap class written by Srini, was not modified.
import java.util.ArrayList;
public class Heap<T extends Comparable<T>>
{
ArrayList<T> heapList;
public Heap()
{
heapList = new ArrayList<T>();
}
public int size()
{
return heapList.size();
}
public boolean isEmpty()
{
return heapList.isEmpty();
}
public void clear()
{
heapList.clear();
}
public void enumerate()
{
System.out.println(heapList);
}
public void add(T item)
{
heapList.add(item);
int index = heapList.size()-1;
int pindex = (index-1)/2;
T parent = heapList.get(pindex);
while (index>0 && item.compareTo(parent)>0)
{
heapList.set(index, parent);
heapList.set(pindex, item);
index = pindex;
pindex = (index-1)/2;
parent = heapList.get(pindex);
}
}
public T deleteMax()
{
if (isEmpty())
{
System.out.println("Heap is empty");
return null;
}
else
{
T ret = heapList.get(0); //get the item in the root. This is the largest item.
T item = heapList.remove(heapList.size()-1); //remove the last item.
if (heapList.size()==0)
return ret; //if there was only one item in the heap to begin with, we are done.
heapList.set(0, item); //otherwise, proceed. Put the item in the root.
int index, lIndex, rIndex, maxIndex;
T maxChild;
boolean found=false;
index = 0;
lIndex = index*2+1;
rIndex = index*2+2;
while (!found)
{
if (lIndex<size()&&rIndex<size()) //case 1: item to be sifted down has two children
{
//find the maxChild and maxIndex
if (heapList.get(lIndex).compareTo(heapList.get(rIndex))>0)
{
maxChild = heapList.get(lIndex);
maxIndex = lIndex;
}
else
{
maxChild = heapList.get(rIndex);
maxIndex = rIndex;
}
//sift down if necessary
if (item.compareTo(maxChild)<0)
{
heapList.set(maxIndex, item);
heapList.set(index, maxChild);
index = maxIndex;
}
else
found = true;
}
else if (lIndex < size()) //case 2: item to be sifted down has only left child
//note: item to be sifted down cannot have only right child - it will violate the complete binary tree property
{
if (item.compareTo(heapList.get(lIndex))<0)
{
heapList.set(index, heapList.get(lIndex));
heapList.set(lIndex,item);
index = lIndex;
}
else
found = true;
}
else //case 3: item to be sifted down has no children
found = true;
lIndex = index*2+1;
rIndex = index*2+2;
}
return ret;
}
}
}