-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.java
More file actions
72 lines (66 loc) · 2.04 KB
/
Copy pathMaxHeap.java
File metadata and controls
72 lines (66 loc) · 2.04 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
public class MaxHeap {
public static void main(String[] args){
maxHeap heap = new maxHeap(20);
heap.insert(5);
heap.insert(3);
heap.insert(17);
heap.insert(10);
heap.insert(84);
heap.insert(19);
System.out.println("Max: " + heap.extractMax()); //Should print 84 as the max.
}
public static class maxHeap{
int[] heap;
int size;
int capacity;
public maxHeap(int capacity){
this.capacity = capacity;
this.heap = new int[capacity];
this.size = 0;
}
private int parent(int i) { return((i - 1) / 2);}
private int left(int i) {return(2 * i + 1);}
private int right(int i) {return(2 * i + 2);}
public void insert(int data){
if(size == capacity){
System.out.println("Heap is Full!");
return;
}
heap[size] = data;
heapifyUp(size);
size++;
}
public int extractMax(){
if(size == 0){
System.out.println("Heap is Empty!");
};
int max = heap[0];
heap[0] = heap[size -1];
size--;
heapifyDown(0);
return max;
}
private void heapifyUp(int i){
while(i > 0 && heap[parent(i)] < heap[i]){
swap(parent(i), i);
i = parent(i);
}
}
private void heapifyDown(int i){
int largest = i;
int l = left(i);
int r = right(i);
if(l < size && heap[l] > heap[largest]) largest = l;
if(r < size && heap[r] > heap[largest]) largest = r;
if(largest != i){
swap(i, largest);
heapifyDown(largest);
}
}
private void swap(int i, int j){
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
}
}