-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeaps.java
More file actions
311 lines (257 loc) · 9.05 KB
/
Heaps.java
File metadata and controls
311 lines (257 loc) · 9.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
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import java.util.*;
// Heaps: complete binary tree that satisfies heap property.
// visualize-array and implement by binary tree.
// heaps are not implemented by class because it requires O(n) time and it is
// discussed in priority queue thena tc should be O(log n).
// cbt complete binary tree is a tree in which every level, except possibly the
// last, is completely filled except the last one, and all nodes are as far left
// as possible.
//for min heap change greater than to less than in add and heapify methods.
public class Heaps {
// --------------------- CUSTOM MAX HEAP (ArrayList) ---------------------
static class MaxHeap {
private ArrayList<Integer> list = new ArrayList<>();
// Add element to heap (O(log n))
public void add(int val) {
list.add(val);
int child = list.size() - 1;
int parent = (child - 1) / 2;
// Heapify up
while (child > 0 && list.get(child) > list.get(parent)) {
swap(child, parent);
child = parent;
parent = (child - 1) / 2;
}
}
// Return root (max element)
public int peek() {
return list.size() == 0 ? -1 : list.get(0);
}
// Remove max (root) from heap (O(log n))
public int remove() {
if (list.isEmpty())
return -1;
int removedValue = list.get(0);
// Move last element to root and remove last
int lastIndex = list.size() - 1;
list.set(0, list.get(lastIndex));
list.remove(lastIndex);
heapifyDown(0);
return removedValue;
}
// Heapify down (O(log n))
private void heapifyDown(int i) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int max = i;
if (left < list.size() && list.get(left) > list.get(max)) {
max = left;
}
if (right < list.size() && list.get(right) > list.get(max)) {
max = right;
}
if (max != i) {
swap(i, max);
heapifyDown(max);
}
}
private void swap(int i, int j) {
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public String toString() {
return list.toString();
}
}
static class Row implements Comparable<Row> {
int soldiers;
int idx;
public Row(int soldiers, int idx) {
this.soldiers = soldiers;
this.idx = idx;
}
@Override
public int compareTo(Row r2) {
if (this.soldiers == r2.soldiers) {
return this.idx - r2.idx;
} else {
return this.soldiers - r2.soldiers;
}
}
}
/*
* ------------------------------------------------------------
* 2) Nearby Cars Problem (k nearest to origin)
* ------------------------------------------------------------
*/
// Car model
static class Car {
int id;
int x;
int y;
Car(int id, int x, int y) {
this.id = id;
this.x = x;
this.y = y;
}
int distSq() {
return x * x + y * y;
}
}
// Method to get k nearest cars
public static List<Car> getNearestCars(List<Car> cars, int k) {
PriorityQueue<Car> maxHeap = new PriorityQueue<>(
(a, b) -> b.distSq() - a.distSq() // max heap: farthest at top
);
for (Car car : cars) {
maxHeap.add(car);
if (maxHeap.size() > k) {
maxHeap.poll();
}
}
return new ArrayList<>(maxHeap);
}
// --------------------- HEAP UTILITIES ---------------------
// Heapify for array-based heap (Used for HeapSort)
public static void heapify(int arr[], int n, int i) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int max = i;
if (left < n && arr[left] > arr[max])
max = left;
if (right < n && arr[right] > arr[max])
max = right;
if (max != i) {
int temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
heapify(arr, n, max);
}
}
// HeapSort using array heap (O(n log n))
public static void heapSort(int arr[]) {
int n = arr.length;
// Step 1: Build max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Step 2: Extract elements
for (int i = n - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
// Minimum cost to connect ropes (Min-Heap)
public static int minCostToConnectRopes(int[] ropes) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int r : ropes)
pq.add(r);
int cost = 0;
while (pq.size() > 1) {
int min1 = pq.remove();
int min2 = pq.remove();
int sum = min1 + min2;
cost += sum;
pq.add(sum);
}
return cost;
}
// ------------WEAKEST SOLIDER-------------
public static void weakestSolider(int arr[][], int k) {
PriorityQueue<Row> ws = new PriorityQueue<>();
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr[0].length; j++) {
count += arr[i][j] == 1 ? 1 : 0;
}
ws.add(new Row(count, i));
}
for (int i = 0; i < k; i++) {
System.out.println("R" + ws.remove().idx);
}
}
// ----------------------------SLIDING WINDOW MAXIMUM-----------------------------
static class SWMpairs implements Comparable<SWMpairs> {
int idx;
int val;
public SWMpairs(int idx, int val) {
this.idx = idx;
this.val = val;
}
@Override
public int compareTo(SWMpairs p2) {
return p2.val - this.val; // max heap
}
public static void slidingWindowMax(int arr[], int k) {
int n = arr.length;
int result[] = new int[n - k + 1];
PriorityQueue<SWMpairs> swm = new PriorityQueue<>();
//store first k elements(first window)
for (int i = 0; i < k; i++) {
swm.add(new SWMpairs(i, arr[i]));
}
result[0] = swm.peek().val;
//process remaining windows
for (int i = k; i < n; i++) {
//remove elements not part of window
while (!swm.isEmpty() && swm.peek().idx <= i - k) {
swm.remove();
}
//add current element
swm.add(new SWMpairs(i, arr[i]));
result[i - k + 1] = swm.peek().val;
}
//print result
for (int x : result) {
System.out.print(x + " ");
}
}
// --------------------- MAIN ---------------------
public static void main(String[] args) {
System.out.println("----- Testing Sliding Window Maximum -----");
int arr1[] = { 1, 3, -1, -3, 5, 3, 6, 7 };
slidingWindowMax(arr1, 3);
System.out.println();
System.out.println("-------Testing weakestSoldiers---------");
int army[][] = { { 1, 0, 0, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 0 }, { 0, 0, 0, 0 } };
weakestSolider(army, 2);
System.out.println("----- Testing Custom MaxHeap -----");
MaxHeap heap = new MaxHeap();
heap.add(10);
heap.add(20);
heap.add(15);
heap.add(30);
System.out.println("Heap after insertions: " + heap);
heap.remove();
System.out.println("Heap after removal: " + heap);
System.out.println("\n----- Testing HeapSort -----");
int arr[] = { 5, 3, 8, 4, 2, 7, 1, 10 };
heapSort(arr);
for (int x : arr)
System.out.print(x + " ");
System.out.println();
System.out.println("\n----- Testing Rope Cost -----");
int[] ropes = { 2, 3, 3, 4, 6 };
System.out.println("Minimum cost to connect ropes: " + minCostToConnectRopes(ropes));
// ----- Test Nearby Cars -----
List<Car> cars = Arrays.asList(
new Car(1, 3, 3),
new Car(2, 5, -1),
new Car(3, -2, 4),
new Car(4, 0, 2));
int k = 2;
List<Car> res = getNearestCars(cars, k);
System.out.println("\nNearest " + k + " cars:");
for (Car c : res) {
System.out.println("Car " + c.id + " at (" + c.x + ", " + c.y + ")");
}
}
}
}