-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomPriorityQueue.java
More file actions
89 lines (77 loc) · 2.28 KB
/
Copy pathCustomPriorityQueue.java
File metadata and controls
89 lines (77 loc) · 2.28 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
package com.example.mywebapp;
public class CustomPriorityQueue<T extends Comparable<T>> {
private T[] heap;
private int size;
private static final int DEFAULT_CAPACITY = 10;
@SuppressWarnings("unchecked")
public CustomPriorityQueue() {
this.heap = (T[]) new Comparable[DEFAULT_CAPACITY];
this.size = 0;
}
public void add(T element) {
if (size == heap.length) {
resize();
}
heap[size] = element;
siftUp(size);
size++;
}
public T poll() {
if (isEmpty()) {
return null;
}
T result = heap[0];
heap[0] = heap[size - 1];
heap[size - 1] = null;
size--;
if (size > 0) {
siftDown(0);
}
return result;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
@SuppressWarnings("unchecked")
private void resize() {
T[] newHeap = (T[]) new Comparable[heap.length * 2];
for (int i = 0; i < heap.length; i++) {
newHeap[i] = heap[i];
}
heap = newHeap;
}
private void siftUp(int index) {
T element = heap[index];
while (index > 0) {
int parentIndex = (index - 1) / 2;
T parent = heap[parentIndex];
if (element.compareTo(parent) <= 0) { // Max-heap: parent should be >= child
break;
}
heap[index] = parent;
index = parentIndex;
}
heap[index] = element;
}
private void siftDown(int index) {
T element = heap[index];
int half = size / 2;
while (index < half) {
int leftChild = 2 * index + 1;
int rightChild = leftChild + 1;
int maxIndex = leftChild;
if (rightChild < size && heap[rightChild].compareTo(heap[leftChild]) > 0) {
maxIndex = rightChild;
}
if (element.compareTo(heap[maxIndex]) >= 0) { // Max-heap: parent should be >= child
break;
}
heap[index] = heap[maxIndex];
index = maxIndex;
}
heap[index] = element;
}
}