Repository navigation
Expand file tree
/
Copy pathMinHeap.java
More file actions
129 lines (100 loc) · 1.94 KB
/
Copy pathMinHeap.java
File metadata and controls
129 lines (100 loc) · 1.94 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
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
package heaps1;
public class MinHeap {
int a[];
int capacity;
int n;
// ignore the a[0]
public MinHeap(int a[]) {
this.a = a;
this.capacity = a.length-1;
this.n = a.length-1;
buildHeap();
}
public MinHeap(int capacity) {
this.capacity = capacity;
n = 0;
a = new int[capacity+1];
}
private void swap(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void insert(int key) throws Exception {
if(n == capacity) throw new Exception("heap is full");
n = n + 1;
a[n] = key;
int i = n;
while(i > 1) {
int parent = i/2;
if(a[parent] > a[i]) {
swap(parent, i);
i = parent;
} else return;
}
}
// deletes and returns the minimum element
int extractMin() throws Exception {
if(n == 0) throw new Exception("Heap is empty");
int result = a[1];
a[1] = a[n];
n--;
int i = 1;
while(i <= n) {
int left = 2*i;
int right = 2*i+1;
int smallest = i;
if(left <= n && a[left] < a[smallest]) {
smallest = left;
}
if(right <= n && a[right] < a[smallest]) {
smallest = right;
}
if(smallest != i) {
swap(smallest, i);
i = smallest;
} else break;
}
return result;
}
// O(logn)
void heapify(int i) {
while(i <= n) {
int left = 2*i;
int right = 2*i+1;
int smallest = i;
if(left <= n && a[left] < a[smallest]) {
smallest = left;
}
if(right <= n && a[right] < a[smallest]) {
smallest = right;
}
if(smallest != i) {
swap(smallest, i);
i = smallest;
} else break;
}
}
// O(n) builds a heap from a given array
void buildHeap() {
for(int i = n; i>0; i--) {
heapify(i);
}
}
void heapSort() throws Exception {
int newN = n;
for(int i = 1; i<=newN; i++) {
int x = extractMin();
System.out.print(x+" ");
}
}
int size() {
return n;
}
void printHeap() {
for(int i = 1; i<=n; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
}