* Created on 2022/9/1.
*
* @author lan
*/
@SuppressWarnings("unchecked")
public class PriorityQueue<T extends Comparable<T>> {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>(Arrays.asList(5, 7, 9, 1, 3, 4, 6, 2, 0));
System.out.println(queue);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
private Object[] queue;
private int len;
public PriorityQueue() {
}
public PriorityQueue(Collection<T> collection) {
for (T t : collection) {
if (t == null) {
throw new NullPointerException();
}
}
queue = collection.toArray(new Object[]{});
len = queue.length;
heapify();
}
public void addAll(Collection<T> collection) {
if (collection != null && !collection.isEmpty()) {
ensureCapacity(collection.size());
for (T t : collection) {
if (t == null) {
throw new NullPointerException();
}
doAdd(t);
}
}
}
private void heapify() {
for (int i = len / 2 - 1; i >= 0; i--) {
siftDown(i);
}
}
/**
* 根据变动的位置,自下而上检查堆
*/
private void siftUp(int i) {
int parent = (i - 1) / 2;
if (parent >= 0) {
if (bigger(i, parent)) {
swap(i, parent);
siftUp(parent);
}
}
}
/**
* 自上而下检查堆
*/
private void siftDown(int i) {
int left = i * 2 + 1;
int right = i * 2 + 2;
int largest = i;
if (left < len && bigger(left, largest)) {
largest = left;
}
if (right < len && bigger(right, largest)) {
largest = right;
}
if (largest != i) {
swap(largest, i);
siftDown(largest);
}
}
private boolean bigger(int i, int j) {
T ti = (T) queue[i];
T tj = (T) queue[j];
return ti.compareTo(tj) > 0;
}
private void doAdd(T e) {
queue[len++] = e;
siftUp(len - 1);
}
private void swap(int i, int j) {
Object tmp = queue[i];
queue[i] = queue[j];
queue[j] = tmp;
}
public void add(T e) {
if (e == null) {
throw new NullPointerException();
}
ensureCapacity(1);
doAdd(e);
}
public T poll() {
if (isEmpty()) {
return null;
}
T res = (T) queue[0];
queue[0] = queue[len - 1];
len--;
siftDown(0);
return res;
}
public T peek() {
return isEmpty() ? null : (T) queue[0];
}
public boolean isEmpty() {
return len == 0;
}
private void ensureCapacity(int required) {
if (queue == null) {
queue = new Object[required * 2];
} else {
if (len + required > queue.length) {
Object[] _queue = new Object[queue.length * 2];
System.arraycopy(queue, 0, _queue, 0, len);
queue = _queue;
}
}
}
@Override
public String toString() {
return "PriorityQueue{" +
"queue=" + Arrays.toString(queue) +
", len=" + len +
'}';
}
}
堆排序实现优先级队列
最新推荐文章于 2024-11-14 21:21:03 发布