In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: If A is a parentnode of B then the key of node A is ordered with respect to the key of node B with the same ordering applying across the heap. Either the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node (this kind of heap is called max heap) or the keys of parent nodes are less than or equal to those of the children and the lowest key is in the root node (min heap). Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree (see figure).

Heaps are usually implemented in an array, and do not require pointers between elements.

Full and almost full binary heaps may be represented in a very space-efficient way using an array alone. The first (or last) element will contain the root. The next two elements of the array contain its children. The next four contain the four children of the two child nodes, etc. Thus the children of the node at position n would be at positions 2n and 2n+1 in a one-based array, or 2n+1 and 2n+2 in a zero-based array. This allows moving up or down the tree by doing simple index computations. Balancing a heap is done by swapping elements which are out of order. As we can build a heap from an array without requiring extra memory (for the nodes, for example), heapsort can be used to sort an array in-place.

The operations commonly performed with a heap are:

  • create-heap: create an empty heap
  • heapify: create a heap out of given array of elements
  • find-max or find-min: find the maximum item of a max-heap or a minimum item of a min-heap, respectively (aka, peek)
  • delete-max or delete-min: removing the root node of a max- or min-heap, respectively
  • increase-key or decrease-key: updating a key within a max- or min-heap, respectively
  • insert: adding a new key to the heap
  • merge: joining two heaps to form a valid new heap containing all the elements of both.
  • meld(h1,h2): Return the heap formed by taking the union of the item-disjoint heaps h1 and h2. Melding destroys h1 and h2.
  • size: return the number of items in the heap.
  • isEmpty(): returns true if the heap is empty, false otherwise.
  • buildHeap(list): builds a new heap from a list of keys.
  • ExtractMin() [or ExtractMax()]: Returns the node of minimum value from a min heap [or maximum value from a max heap] after removing it from the heap
  • Union(): Creates a new heap by joining two heaps given as input.
  • Shift-up: Move a node up in the tree, as long as needed (depending on the heap condition: min-heap or max-heap)
  • Shift-down: Move a node down in the tree, similar to Shift-up

Different types of heaps implement the operations in different ways, but notably, insertion is often done by adding the new element at the end of the heap in the first available free space. This will tend to violate the heap property, and so the elements are then reordered until the heap property has been reestablished. Construction of a binary (or d-ary) heap out of a given array of elements may be performed faster than a sequence of consecutive insertions into an originally empty heap using the classic Floyd's algorithm, with the worst-case number of comparisons equal to 2N − 2s2(N) − e2(N) (for a binary heap), wheres2(N) is the sum of all digits of the binary representation of N and e2(N) is the exponent of 2 in the prime factorization of N

(reference from:https://en.wikipedia.org/wiki/Heap_(data_structure))

Binary heap

There are several types of heaps, but in the current article we are going to discuss the binary heap. For short, let's call it just "heap". It is used to implement priority queue ADTand in the heapsort algorithm. Heap is a complete binary tree, which answers to the heap property.

http://www.algolist.net/Data_structures/Binary_heap

Implementation in java

路径:commons-collections-3.2.1-src/src/java/org/apache/commons/collections/BinaryHeap.java

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections; import java.util.AbstractCollection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException; /***
* Binary heap implementation of <code>PriorityQueue</code>.
* <p>
* The <code>PriorityQueue</code> interface has now been replaced for most uses
* by the <code>Buffer</code> interface. This class and the interface are
* retained for backwards compatibility. The intended replacement is
* {@link org.apache.commons.collections.buffer.PriorityBuffer PriorityBuffer}.
* <p>
* The removal order of a binary heap is based on either the natural sort
* order of its elements or a specified {@link Comparator}. The
* {@link #pop()} method always returns the first element as determined
* by the sort order. (The <code>isMinHeap</code> flag in the constructors
* can be used to reverse the sort order, in which case {@link #pop()}
* will always remove the last element.) The removal order is
* <i>not</i> the same as the order of iteration; elements are
* returned by the iterator in no particular order.
* <p>
* The {@link #insert(Object)} and {@link #pop()} operations perform
* in logarithmic time. The {@link #peek()} operation performs in constant
* time. All other operations perform in linear time or worse.
* <p>
* Note that this implementation is not synchronized. Use SynchronizedPriorityQueue
* to provide synchronized access to a <code>BinaryHeap</code>:
*
* <pre>
* PriorityQueue heap = new SynchronizedPriorityQueue(new BinaryHeap());
* </pre>
*
* @deprecated Replaced by PriorityBuffer in buffer subpackage.
* Due to be removed in v4.0.
* @since Commons Collections 1.0
* @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
*
* @author Peter Donald
* @author Ram Chidambaram
* @author Michael A. Smith
* @author Paul Jack
* @author Stephen Colebourne
*/
public final class BinaryHeap extends AbstractCollection
implements PriorityQueue, Buffer { /***
* The default capacity for a binary heap.
*/
private final static int DEFAULT_CAPACITY = 13;
/***
* The number of elements currently in this heap.
*/
int m_size; // package scoped for testing
/***
* The elements in this heap.
*/
Object[] m_elements; // package scoped for testing
/***
* If true, the first element as determined by the sort order will
* be returned. If false, the last element as determined by the
* sort order will be returned.
*/
boolean m_isMinHeap; // package scoped for testing
/***
* The comparator used to order the elements
*/
Comparator m_comparator; // package scoped for testing /***
* Constructs a new minimum binary heap.
*/
public BinaryHeap() {
this(DEFAULT_CAPACITY, true);
} /***
* Constructs a new <code>BinaryHeap</code> that will use the given
* comparator to order its elements.
*
* @param comparator the comparator used to order the elements, null
* means use natural order
*/
public BinaryHeap(Comparator comparator) {
this();
m_comparator = comparator;
} /***
* Constructs a new minimum binary heap with the specified initial capacity.
*
* @param capacity The initial capacity for the heap. This value must
* be greater than zero.
* @throws IllegalArgumentException
* if <code>capacity</code> is &lt;= <code>0</code>
*/
public BinaryHeap(int capacity) {
this(capacity, true);
} /***
* Constructs a new <code>BinaryHeap</code>.
*
* @param capacity the initial capacity for the heap
* @param comparator the comparator used to order the elements, null
* means use natural order
* @throws IllegalArgumentException
* if <code>capacity</code> is &lt;= <code>0</code>
*/
public BinaryHeap(int capacity, Comparator comparator) {
this(capacity);
m_comparator = comparator;
} /***
* Constructs a new minimum or maximum binary heap
*
* @param isMinHeap if <code>true</code> the heap is created as a
* minimum heap; otherwise, the heap is created as a maximum heap
*/
public BinaryHeap(boolean isMinHeap) {
this(DEFAULT_CAPACITY, isMinHeap);
} /***
* Constructs a new <code>BinaryHeap</code>.
*
* @param isMinHeap true to use the order imposed by the given
* comparator; false to reverse that order
* @param comparator the comparator used to order the elements, null
* means use natural order
*/
public BinaryHeap(boolean isMinHeap, Comparator comparator) {
this(isMinHeap);
m_comparator = comparator;
} /***
* Constructs a new minimum or maximum binary heap with the specified
* initial capacity.
*
* @param capacity the initial capacity for the heap. This value must
* be greater than zero.
* @param isMinHeap if <code>true</code> the heap is created as a
* minimum heap; otherwise, the heap is created as a maximum heap.
* @throws IllegalArgumentException
* if <code>capacity</code> is <code>&lt;= 0</code>
*/
public BinaryHeap(int capacity, boolean isMinHeap) {
if (capacity <= 0) {
throw new IllegalArgumentException("invalid capacity");
}
m_isMinHeap = isMinHeap; //+1 as 0 is noop
m_elements = new Object[capacity + 1];
} /***
* Constructs a new <code>BinaryHeap</code>.
*
* @param capacity the initial capacity for the heap
* @param isMinHeap true to use the order imposed by the given
* comparator; false to reverse that order
* @param comparator the comparator used to order the elements, null
* means use natural order
* @throws IllegalArgumentException
* if <code>capacity</code> is <code>&lt;= 0</code>
*/
public BinaryHeap(int capacity, boolean isMinHeap, Comparator comparator) {
this(capacity, isMinHeap);
m_comparator = comparator;
} //-----------------------------------------------------------------------
/***
* Clears all elements from queue.
*/
public void clear() {
m_elements = new Object[m_elements.length]; // for gc
m_size = 0;
} /***
* Tests if queue is empty.
*
* @return <code>true</code> if queue is empty; <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return m_size == 0;
} /***
* Tests if queue is full.
*
* @return <code>true</code> if queue is full; <code>false</code>
* otherwise.
*/
public boolean isFull() {
//+1 as element 0 is noop
return m_elements.length == m_size + 1;
} /***
* Inserts an element into queue.
*
* @param element the element to be inserted
*/
public void insert(Object element) {
if (isFull()) {
grow();
}
//percolate element to it's place in tree
if (m_isMinHeap) {
percolateUpMinHeap(element);
} else {
percolateUpMaxHeap(element);
}
} /***
* Returns the element on top of heap but don't remove it.
*
* @return the element at top of heap
* @throws NoSuchElementException if <code>isEmpty() == true</code>
*/
public Object peek() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException();
} else {
return m_elements[1];
}
} /***
* Returns the element on top of heap and remove it.
*
* @return the element at top of heap
* @throws NoSuchElementException if <code>isEmpty() == true</code>
*/
public Object pop() throws NoSuchElementException {
final Object result = peek();
m_elements[1] = m_elements[m_size--]; // set the unused element to 'null' so that the garbage collector
// can free the object if not used anywhere else.(remove reference)
m_elements[m_size + 1] = null; if (m_size != 0) {
// percolate top element to it's place in tree
if (m_isMinHeap) {
percolateDownMinHeap(1);
} else {
percolateDownMaxHeap(1);
}
} return result;
} /***
* Percolates element down heap from the position given by the index.
* <p>
* Assumes it is a minimum heap.
*
* @param index the index for the element
*/
protected void percolateDownMinHeap(final int index) {
final Object element = m_elements[index];
int hole = index; while ((hole * 2) <= m_size) {
int child = hole * 2; // if we have a right child and that child can not be percolated
// up then move onto other child
if (child != m_size && compare(m_elements[child + 1], m_elements[child]) < 0) {
child++;
} // if we found resting place of bubble then terminate search
if (compare(m_elements[child], element) >= 0) {
break;
} m_elements[hole] = m_elements[child];
hole = child;
} m_elements[hole] = element;
} /***
* Percolates element down heap from the position given by the index.
* <p>
* Assumes it is a maximum heap.
*
* @param index the index of the element
*/
protected void percolateDownMaxHeap(final int index) {
final Object element = m_elements[index];
int hole = index; while ((hole * 2) <= m_size) {
int child = hole * 2; // if we have a right child and that child can not be percolated
// up then move onto other child
if (child != m_size && compare(m_elements[child + 1], m_elements[child]) > 0) {
child++;
} // if we found resting place of bubble then terminate search
if (compare(m_elements[child], element) <= 0) {
break;
} m_elements[hole] = m_elements[child];
hole = child;
} m_elements[hole] = element;
} /***
* Percolates element up heap from the position given by the index.
* <p>
* Assumes it is a minimum heap.
*
* @param index the index of the element to be percolated up
*/
protected void percolateUpMinHeap(final int index) {
int hole = index;
Object element = m_elements[hole];
while (hole > 1 && compare(element, m_elements[hole / 2]) < 0) {
// save element that is being pushed down
// as the element "bubble" is percolated up
final int next = hole / 2;
m_elements[hole] = m_elements[next];
hole = next;
}
m_elements[hole] = element;
} /***
* Percolates a new element up heap from the bottom.
* <p>
* Assumes it is a minimum heap.
*
* @param element the element
*/
protected void percolateUpMinHeap(final Object element) {
m_elements[++m_size] = element;
percolateUpMinHeap(m_size);
} /***
* Percolates element up heap from from the position given by the index.
* <p>
* Assume it is a maximum heap.
*
* @param index the index of the element to be percolated up
*/
protected void percolateUpMaxHeap(final int index) {
int hole = index;
Object element = m_elements[hole]; while (hole > 1 && compare(element, m_elements[hole / 2]) > 0) {
// save element that is being pushed down
// as the element "bubble" is percolated up
final int next = hole / 2;
m_elements[hole] = m_elements[next];
hole = next;
} m_elements[hole] = element;
} /***
* Percolates a new element up heap from the bottom.
* <p>
* Assume it is a maximum heap.
*
* @param element the element
*/
protected void percolateUpMaxHeap(final Object element) {
m_elements[++m_size] = element;
percolateUpMaxHeap(m_size);
} /***
* Compares two objects using the comparator if specified, or the
* natural order otherwise.
*
* @param a the first object
* @param b the second object
* @return -ve if a less than b, 0 if they are equal, +ve if a greater than b
*/
private int compare(Object a, Object b) {
if (m_comparator != null) {
return m_comparator.compare(a, b);
} else {
return ((Comparable) a).compareTo(b);
}
} /***
* Increases the size of the heap to support additional elements
*/
protected void grow() {
final Object[] elements = new Object[m_elements.length * 2];
System.arraycopy(m_elements, 0, elements, 0, m_elements.length);
m_elements = elements;
} /***
* Returns a string representation of this heap. The returned string
* is similar to those produced by standard JDK collections.
*
* @return a string representation of this heap
*/
public String toString() {
final StringBuffer sb = new StringBuffer(); sb.append("[ "); for (int i = 1; i < m_size + 1; i++) {
if (i != 1) {
sb.append(", ");
}
sb.append(m_elements[i]);
} sb.append(" ]"); return sb.toString();
} /***
* Returns an iterator over this heap's elements.
*
* @return an iterator over this heap's elements
*/
public Iterator iterator() {
return new Iterator() { private int index = 1;
private int lastReturnedIndex = -1; public boolean hasNext() {
return index <= m_size;
} public Object next() {
if (!hasNext()) throw new NoSuchElementException();
lastReturnedIndex = index;
index++;
return m_elements[lastReturnedIndex];
} public void remove() {
if (lastReturnedIndex == -1) {
throw new IllegalStateException();
}
m_elements[ lastReturnedIndex ] = m_elements[ m_size ];
m_elements[ m_size ] = null;
m_size--;
if( m_size != 0 && lastReturnedIndex <= m_size) {
int compareToParent = 0;
if (lastReturnedIndex > 1) {
compareToParent = compare(m_elements[lastReturnedIndex],
m_elements[lastReturnedIndex / 2]);
}
if (m_isMinHeap) {
if (lastReturnedIndex > 1 && compareToParent < 0) {
percolateUpMinHeap(lastReturnedIndex);
} else {
percolateDownMinHeap(lastReturnedIndex);
}
} else { // max heap
if (lastReturnedIndex > 1 && compareToParent > 0) {
percolateUpMaxHeap(lastReturnedIndex);
} else {
percolateDownMaxHeap(lastReturnedIndex);
}
}
}
index--;
lastReturnedIndex = -1;
} };
} /***
* Adds an object to this heap. Same as {@link #insert(Object)}.
*
* @param object the object to add
* @return true, always
*/
public boolean add(Object object) {
insert(object);
return true;
} /***
* Returns the priority element. Same as {@link #peek()}.
*
* @return the priority element
* @throws BufferUnderflowException if this heap is empty
*/
public Object get() {
try {
return peek();
} catch (NoSuchElementException e) {
throw new BufferUnderflowException();
}
} /***
* Removes the priority element. Same as {@link #pop()}.
*
* @return the removed priority element
* @throws BufferUnderflowException if this heap is empty
*/
public Object remove() {
try {
return pop();
} catch (NoSuchElementException e) {
throw new BufferUnderflowException();
}
} /***
* Returns the number of elements in this heap.
*
* @return the number of elements in this heap
*/
public int size() {
return m_size;
} }

binary heap的更多相关文章

  1. 堆(Heap)和二叉堆(Binary heap)

    堆(Heap) The operations commonly performed with a heap are: create-heap: create an empty heap heapify ...

  2. C++之Binary Heap/Max Heap

    #include <iostream> #include <time.h> #include <random> using namespace std; //Bin ...

  3. [Swift]有用的Binary Heap Type类

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  4. 二叉堆(binary heap)

    堆(heap) 亦被称为:优先队列(priority queue),是计算机科学中一类特殊的数据结构的统称.堆通常是一个可以被看做一棵树的数组对象.在队列中,调度程序反复提取队列中第一个作业并运行,因 ...

  5. Binary Heap(二叉堆) - 堆排序

    这篇的主题主要是Heapsort(堆排序),下一篇ADT数据结构随笔再谈谈 - 优先队列(堆). 首先,我们先来了解一点与堆相关的东西.堆可以实现优先队列(Priority Queue),看到队列,我 ...

  6. 二叉堆(binary heap)—— 优先队列的实现

    二叉堆因为对应着一棵完全二叉树,因而可以通过线性数组的方式实现. 注意,数组第 0 个位置上的元素,作为根,还是第 1 个位置上的元素作为根? 本文给出的实现,以数组第 1 个位置上的元素作为根,则其 ...

  7. 纸上谈兵:左倾堆(leftist heap)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 我们之前讲解了堆(heap)的概念.堆是一个优先队列.每次从堆中取出的元素都是堆中 ...

  8. 纸上谈兵:堆(heap)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 堆(heap)又被为优先队列(priority queue).尽管名为优先队列,但 ...

  9. Erlang数据类型的表示和实现(5)——binary

    binary 是 Erlang 中一个具有特色的数据结构,用于处理大块的“原始的”字节块.如果没有 binary 这种数据类型,在 Erlang 中处理字节流的话可能还需要像列表或元组这样的数据结构. ...

随机推荐

  1. NWERC 2012 Problem A Admiral

    一个最小费用最大流的简单建模题: 比赛的时候和小珺合力想到了这个题目的模型: 方法:拆点+边的容量为1 这样就可以保证他们不会在点上和边上相遇了! 感谢刘汝佳大神的模板,让我这个网络流的小白A了这个题 ...

  2. (转)未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService~~导出!解决方案。

    今天刚到公司,打开VS2012准备些个小程序练练手,结果打开C#控制台程序创建时弹出个出错警告,于是呼赶紧跑到百度娘那里问问. 百度一番之后,找到了两篇文章: vs2012建立c++项目为啥会这样? ...

  3. 李洪强iOS开发Swift篇—09_属性

    李洪强iOS开发Swift篇—09_属性 一.类的定义 Swift与Objective-C定义类的区别 Objective-C:一般需要2个文件,1个.h声明文件和1个.m实现文件 Swift:只需要 ...

  4. HANDLE HINSTANCE HWND CWnd CDC

    HANDLE HINSTANCE HWND CWnd CDC 句柄:   柄,把柄 例如一个锅的手柄,你只要抓住了它,你就可以很好地操作那个锅,不过很明显你只能通过锅的手柄来做一些诸如炒菜之类的事,你 ...

  5. 最简单的CRC32源码---逐BIT法

    CRC其实也就那么回事,却在网上被传得神乎其神.单纯从使用角度来说,只需要搞明白模二除法,再理解一些偷懒优化的技巧,就能写出自己的CRC校验程序. 下面的代码完全是模拟手算过程的,效率是最低的,发出来 ...

  6. Android之获得内存剩余大小与总大小

    方法一: 如何查看android对应用的内存限制 每款手机对应用的限制都是不一样的,毕竟硬件不同,我们可以使用如下方式来查看单独的应用可使用的最大内存: 执行命令: adb shell getprop ...

  7. Linux 下报错:A Java RunTime Environment (JRE) or Java Development Kit (JDK) must解决方案

    一.报错环境:在Linux mint下,前几天还用得很好的的eclipse,今天开机不知为什么这样. Linux 下报错:A Java RunTime Environment (JRE) or Jav ...

  8. Oracle core05_事务和一致性

    事务和一致性 oracle的redo和undo机制保证了数据库的ACID特性,以及高性能和可恢复特性. redo的数据是记录着数据块变更的顺序的正向数据流, commit时,保证redo同步持久化,保 ...

  9. bzoj2038

    网上大片的莫队算法题解,先orz一下莫队什么不会莫队?没事我来篇低端的分块大法好啊,我们知道对于区间[l,r]答案是S/P P是一下子可以算出来的,S=∑(pj-1)*pj/2 pj表示区间内颜色为j ...

  10. HDOJ/HDU 1241 Oil Deposits(经典DFS)

    Problem Description The GeoSurvComp geologic survey company is responsible for detecting underground ...