📄 binaryheap.java
字号:
/*
* Copyright 2001-2004 The Apache Software Foundation
*
* Licensed 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: 155406 $ $Date: 2005-02-26 12:55:26 +0000 (Sat, 26 Feb 2005) $
*
* @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 <= <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 <= <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><= 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><= 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.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -