summaryrefslogtreecommitdiff
path: root/projects/project4_huffman_tree/MinHeap.java
blob: 3b462879b3507dc1fcf73b343bb03255d23f1786 (plain)
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
129
130
131
132
public class MinHeap<T extends Comparable<? super T>> implements MinHeapInterface<T>
{
	private T[] heap;
	private int lastIndex;
	private static final int DEFAULT_INITIAL_CAPACITY = 25;
	
	public MinHeap()
	{
		this(DEFAULT_INITIAL_CAPACITY);
	}
	
	public MinHeap(int initialCapacity)
	{
		@SuppressWarnings("unchecked")
		T[] tempHeap = (T[]) new Comparable[initialCapacity];
		
		heap = tempHeap;
		lastIndex = 0;
	}
	
	public void add(T newEntry)
	{
		lastIndex++;
		ensureCapacity();
		
		int newIndex = lastIndex;
		int parentIndex = newIndex / 2;
		
		while((parentIndex > 0) && newEntry.compareTo(heap[parentIndex]) < 0)
		{
			heap[newIndex] = heap[parentIndex];
			newIndex = parentIndex;
			parentIndex = newIndex / 2;
		}
		
		heap[newIndex] = newEntry;
	}

	public T removeMin()
	{
		T root = null;
		
		if(!isEmpty())
		{
			root = heap[1];
			heap[1] = heap[lastIndex];
			lastIndex--;
			reheap(1);
		}
		
		return root;
	}

	public T getMin()
	{
		T root = null;
		
		if(!isEmpty())
		{
			root = heap[1];
		}
		
		return root;
	}

	public boolean isEmpty()
	{
		return lastIndex < 1;
	}

	public int getSize()
	{
		return lastIndex;
	}

	public void clear()
	{
		for(int i = 0; i <= lastIndex; i++)
		{
			heap[i] = null;
		}
		
		lastIndex = 0;
	}

	private void ensureCapacity()
	{
		if(heap.length == lastIndex)
		{
			@SuppressWarnings("unchecked")
			T[] tempHeap = (T[]) new Comparable[heap.length * 2];
			
			for(int i = 0; i < lastIndex; i++)
			{
				tempHeap[i] = heap[i];
			}
			
			heap = tempHeap;
		}
	}

	private void reheap(int rootIndex)
	{
		boolean done = false;
		T orphan = heap[rootIndex];
		int leftChildIndex = rootIndex * 2;
		
		while(!done && (leftChildIndex <= lastIndex))
		{
			int smallerChildIndex = leftChildIndex;
			int rightChildIndex = leftChildIndex + 1;
			if((rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[smallerChildIndex]) < 0)
			{
				smallerChildIndex = rightChildIndex;
			}
			
			if(orphan.compareTo(heap[smallerChildIndex]) > 0)
			{
				heap[rootIndex] = heap[smallerChildIndex];
				rootIndex = smallerChildIndex;
				leftChildIndex = rootIndex * 2;
			}
			else
			{
				done = true;
			}
		}
		
		heap[rootIndex] = orphan;
	}
}