java简易优先队列(小顶堆)
class Heap{
private int[] heap;
private int size;
public Heap(int n)
{
heap = new int[n + 1];
size = 0;
}
public void offer(int num)
{
int father = ((size - 1) >> 1), index = size;
heap[index] = num;
while (father >= 0)
{
if (heap[father] > heap[index]) swap(index, father);
index = father;
father = ((father - 1) >> 1);
}
size++;
}
public int poll()
{
int res = heap[0];
swap(0, size - 1);
int temp = heap[0];
for (int i = 1;i < size - 1;i = (i << 1) + 1)
{
if (i + 1 < size - 1 && heap[i] > heap[i + 1]) i++;
if (temp < heap[i]) break;
heap[((i - 1) >> 1)] = heap[i];
heap[i] = temp;
}
size--;
return res;
}
private void swap(int indexA, int indexB)
{
int temp = heap[indexA];
heap[indexA] = heap[indexB];
heap[indexB] = temp;
}
}