1、堆
1.1、堆的作用
1.2、堆的概念
堆首先是一顆二叉樹,但他是完全二叉樹
1.3、堆中添加元素
1.4、從頭部刪除元素
1.5、從中間刪除元素
1.6、構建初始堆
1.7、遍歷和查找
1.8、小結
2、PriorityQueue分析
2.1、實現原理
內部成員組成:
底層就是個數組
private static final int DEFAULT_INITIAL_CAPACITY = 11;
//存儲元素的數組
transient Object[] queue; // non-private to simplify nested class access
//表示當前元素的個數
private int size = 0;
//比較器
private final Comparator<? super E> comparator;
//記錄修改次數
transient int modCount = 0; // non-private to simplify nested class access
2.2、構造方法
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
public PriorityQueue(int initialCapacity) {
this(initialCapacity, null);
}
public PriorityQueue(Comparator<? super E> comparator) {
this(DEFAULT_INITIAL_CAPACITY, comparator);
}
public PriorityQueue(int initialCapacity,
Comparator<? super E> comparator) {
// Note: This restriction of at least one is not actually needed,
// but continues for 1.5 compatibility
if (initialCapacity < 1)
throw new IllegalArgumentException();
this.queue = new Object[initialCapacity];
this.comparator = comparator;
}
2.3、offer方法
隊列爲空直接插入
否則將數據插入到隊列尾部
* 數組容量不夠時進行擴容
對堆進行向上調整
//添加元素入隊
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
modCount++;
int i = size;
if (i >= queue.length)//首先保證數組長度是夠的,如果不夠,調用grow方法動態擴展
grow(i + 1);
size = i + 1;//增加長度
if (i == 0)//如果是第一次添加,直接添加到第一個位置即可
queue[0] = e;
else //否則將其放到最後一個位置,但同時向上調整,直至滿足堆的性質
siftUp(i, e);
return true;
}
//數組擴容
private void grow(int minCapacity) {
int oldCapacity = queue.length;
// 如果原長度比較小,大概擴展爲兩倍,
//否則就是增加50%
int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
// overflow-conscious code
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
queue = Arrays.copyOf(queue, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
//確保堆的定義m,堆的調整
private void siftUp(int k, E x) {
//根據是否有comparator分了兩種情況
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
@SuppressWarnings("unchecked")
//向上調整
//k表示插入位置,x表示新元素,k初始化等於數組大小,即在最後一個位置插入
private void siftUpUsingComparator(int k, E x) {
//尋找插入位置k
while (k > 0) {
//父節點在數組中直接除2
int parent = (k - 1) >>> 1;
Object e = queue[parent];
//如果新元素x大於父節點(e),則滿足堆的性質,退出循環
if (comparator.compare(x, (E) e) >= 0)
break;
//否則,將父節點下移
queue[k] = e;
k = parent;
}
queue[k] = x;
}
2.4、peek查看頭部元素
@SuppressWarnings("unchecked")
public E peek() {
//查看頭部元素就是返回第一個元素
return (size == 0) ? null : (E) queue[0];
}
2.5、刪除頭部元素
//刪除頭部元素
@SuppressWarnings("unchecked")
public E poll() {
if (size == 0)
return null;
int s = --size;
modCount++;
//返回結果爲第一個元素
E result = (E) queue[0];
//x指向最後一個元素
E x = (E) queue[s];
//將最後元素設置爲null
queue[s] = null;
if (s != 0)
//調用siftDown將原來的最後元素x插入到頭部並調整堆
siftDown(0, x);
return result;
}
//向下調整堆
private void siftDown(int k, E x) {
if (comparator != null)
siftDownUsingComparator(k, x);
else
siftDownComparable(k, x);
}
//向下調整堆
@SuppressWarnings("unchecked")
/**
* k表示最終插入的位置,初始爲0
* x表示原來的最後元素
* 代碼的主要部分是:向下尋找x真正應該插入的位置,這個位置用k表示
*/
private void siftDownUsingComparator(int k, E x) {
int half = size >>> 1;
//k<half表示編號爲k的節點有孩子節點,沒有孩子節點,就不需要找了
while (k < half) {
int child = (k << 1) + 1;
Object c = queue[child];
int right = child + 1;
if (right < size &&
comparator.compare((E) c, (E) queue[right]) > 0)
c = queue[child = right];
if (comparator.compare(x, (E) c) <= 0)
break;
queue[k] = c;
k = child;
}
queue[k] = x;
}
2.6、根據值刪除元素
//根據值刪除元素
public boolean remove(Object o) {
//限號元素的位置
int i = indexOf(o);
if (i == -1)
return false;
else {
removeAt(i);
return true;
}
}
//遍歷數組
private int indexOf(Object o) {
if (o != null) {
for (int i = 0; i < size; i++)
if (o.equals(queue[i]))
return i;
}
return -1;
}
//刪除
@SuppressWarnings("unchecked")
private E removeAt(int i) {
// assert i >= 0 && i < size;
modCount++;
int s = --size;
//如果刪除元素在最後宇哥位置,直接刪除
if (s == i) // removed last element
queue[i] = null;
else {
//否則移動最後一個元素到位置i並進行堆調整
E moved = (E) queue[s];
queue[s] = null;
//代碼先向下調整,
siftDown(i, moved);
//如果沒有調整過,接本辦法還需要向上調整
if (queue[i] == moved) {
siftUp(i, moved);
if (queue[i] != moved)
//如果調整過,返回值爲moved
return moved;
}
}
return null;
}
2.7、容器構建優先級隊列
//從一個既不是PriorityQueue也不是SortedSet的容器構造堆
private void initFromCollection(Collection<? extends E> c) {
//初始化queue和size
initElementsFromCollection(c);
//自底向上合併構建對
heapify();
}
//初始化queue和size
private void initElementsFromCollection(Collection<? extends E> c) {
Object[] a = c.toArray();
// If c.toArray incorrectly doesn't return Object[], copy it.
if (a.getClass() != Object[].class)
a = Arrays.copyOf(a, a.length, Object[].class);
int len = a.length;
if (len == 1 || this.comparator != null)
for (int i = 0; i < len; i++)
if (a[i] == null)
throw new NullPointerException();
this.queue = a;
this.size = a.length;
}
@SuppressWarnings("unchecked")
private void heapify() {
for (int i = (size >>> 1) - 1; i >= 0; i--)
siftDown(i, (E) queue[i]);
}