addElement操做
將給定的元素添加到堆中的恰當位置,維持該堆的徹底性屬性和有序屬性。html
若是元素不是Comparable類型的,則會拋出異常。這是爲了讓元素可比較,能夠維持堆的有序屬性。java
public void addElement(T obj) { if (count == tree.length) expandCapacity(); tree[count] = obj; count++; modCount++; if (count > 1) heapifyAdd(); } private void heapifyAdd() { T temp; int next = count - 1; temp = tree[next]; while ((next != 0) && (((Comparable) temp).compareTo(tree[(next - 1) / 2]) < 0)) { tree[next] = tree[(next - 1) / 2]; next = (next - 1) / 2; } tree[next] = temp; }
removeMin操做
刪除堆的最小元素:刪除堆的最小元素而且返回。node
最小元素位於根結點,刪除掉根結點,爲了維持樹的徹底性,要找一個元素來替代它,那麼只有一個能替換根的合法元素,且它是存儲在樹中最末一片葉子上的元素。最末的葉子是h層上最右邊的葉子。git
public T removeMin() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("ArrayHeap"); T minElement = tree[0]; tree[0] = tree[count - 1]; heapifyRemove(); count--; modCount--; return minElement; } /** * Reorders this heap to maintain the ordering property * after the minimum element has been removed. */ private void heapifyRemove() { T temp; int node = 0; int left = 1; int right = 2; int next; if ((tree[left] == null) && (tree[right] == null)) next = count; else if (tree[right] == null) next = left; else if (((Comparable) tree[left]).compareTo(tree[right]) < 0) next = left; else next = right; temp = tree[node]; while ((next < count) && (((Comparable) tree[next]).compareTo(temp) < 0)) { tree[node] = tree[next]; node = next; left = 2 * node + 1; right = 2 * (node + 1); if ((tree[left] == null) && (tree[right] == null)) next = count; else if (tree[right] == null) next = left; else if (((Comparable) tree[left]).compareTo(tree[right]) < 0) next = left; else next = right; } tree[node] = temp; }
public T findMin() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("ArrayHeap"); return tree[0]; }·
雖然最小堆根本就不是一個隊列,可是它卻提供了一個高效的優先級隊列實現。api
heapifyAdd:完成對堆的任何重排序,從那片新葉子開始向上處理至根處數組
添加元素對於複雜度(複雜度爲:2*logn + 1 +logn,即o(logn)):數據結構
heapifyRemove:進行重排序(從根向下)學習
刪除根元素對於複雜度(複雜度爲:2*logn + logn + 1,即o(logn))this
該元素在堆根處,只需返回根處便可.net
複雜度爲o(1)
將count值遞增1。
時間複雜度爲 1 + log ,爲 O(logn)。
返回初始的根元素,並將count值減1。
時間複雜度爲 1 + log ,爲 O(logn)。
指向索引爲0
時間複雜度爲O(1)。
例如
書中定義:
優先隊列是一個服從兩個有序規則的集合。首先,具備更高優先級的項排在前面。其次,具備相同優先級的項按先進先出的規則排列。
public void addElement(T obj) { HeapNode<T> node = new HeapNode<T>(obj); if (root == null) root = node; else { HeapNode<T> nextParent = getNextParentAdd(); if (nextParent.getLeft() == null) nextParent.setLeft(node); else nextParent.setRight(node); node.setParent(nextParent); } lastNode = node; modCount++; if (size() > 1) heapifyAdd(); }
其中有段代碼: node.setParent(nextParent);
在add方法中已經明確代表nextParent.setLeft(node);
那設置node結點的父節點是newParent有什麼意義?
代碼行數(新增/累積) | 博客量(新增/累積) | 學習時間(新增/累積) | |
---|---|---|---|
目標 | 5000行 | 30篇 | 400小時 |
第一週 | 0/0 | 1/1 | 8/8 |
第二週 | 671/671 | 1/2 | 17/25 |
第三週 | 345/1016 | 1/3 | 15/40 |
第四周 | 405/1421 | 2/5 | 23/63 |
第五週 | 1202/2623 | 1/5 | 20/83 |
第六週 | 1741/4364 | 1/6 | 20/103 |
第七週 | 400/4764 | 1/7 | 20/123 |
第八週 | 521/5285 | 2/9 | 24/147 |