-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.java
More file actions
73 lines (66 loc) · 2.05 KB
/
Copy pathMinHeap.java
File metadata and controls
73 lines (66 loc) · 2.05 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
73
public class MinHeap {
public static void main(String[] args){
minHeap heap = new minHeap(10);
heap.insert(5);
heap.insert(3);
heap.insert(17);
heap.insert(10);
heap.insert(84);
heap.insert(19);
System.out.println("Min: " + heap.extractMin()); //Should print 3 as the min.
}
public static class minHeap{
int[] heap;
int size;
int capacity;
public minHeap(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;
heapifyDown(0);
size++;
}
public int extractMin(){
if(size == 0){
System.out.println("Heap is Empty!");
}
int min = heap[0];
heap[0] = heap[size -1];
size--;
heapifyUp(size);
return min;
}
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 smallest = i;
int l = left(i);
int r = right(i);
if(l < size && heap[l] < heap[smallest]) smallest = l;
if(r < size && heap[r] < heap[smallest]) smallest = r;
if(smallest != i){
swap(i, smallest);
heapifyDown(smallest);
}
}
private void swap(int i, int j){
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
}
}