java 基于堆的最小优先级队列实现i java。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 基于堆的最小优先级队列实现i java。相关的知识,希望对你有一定的参考价值。
//
//public interface PQ<E>{
//
// E getMin();
//
// E removeMin();
//
// void insert(E e);
//
// int size();
//
// boolean isEmpty();
//
//
//}
public class MinHeapPQ<E extends Comparable<? super E>> implements PQ<E> {
private static final int INITIAL_CAPACITY = 3;
E[] elements;
int size = 0 ;
public MinHeapPQ(){
@SuppressWarnings("unchecked")
E[] elements = (E[]) new Comparable[INITIAL_CAPACITY];
this.elements = elements;
}
public MinHeapPQ(Collection<? extends E> source){
@SuppressWarnings("unchecked")
E[] elements = (E[]) source.toArray();
size = source.size();
this.elements = elements;
constructHeap();
}
@Override
public E getMin() {
return elements[0];
}
@Override
public E removeMin() {
if( isEmpty())
throw new NoSuchElementException("Empty Queee Error");
E ret = elements[0];
swap(0 , size -1);
size--;
elements[size] = null;
heapify(0);
if(size < elements.length/4)
ensureCapacity(Math.max(2*size , INITIAL_CAPACITY));
return ret;
}
@Override
public void insert( E element) {
if(size == elements.length)
ensureCapacity(2 * size);
elements[size] = element;
int index = size;
while( greater(parent(index) , index) )
{
swap(parent(index) , index);
index=parent(index);
}
size++;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size==0;
}
private void constructHeap(){
for(int i = size/2 ; i >=0 && size>0 ; i--)
heapify(i);
}
private void heapify(int index){
int min = index;
if( left(index) < size() && greater(min, left(index)))
min = left(index);
if( right(index) < size() && greater(min, right(index)))
min = right(index);
if(min!=index){
swap(min,index);
heapify(min);
}
}
private int parent(int i){
assert i >=0;
return i/2;
}
private int left(int i){
assert i >=0;
return 2*i;
}
private int right(int i){
assert i >=0;
return 2*i+1;
}
private boolean greater(int i,int j){
return elements[i].compareTo(elements[j]) > 0;
}
private void swap(int i , int j){
assert i < elements.length;
assert j < elements.length;
assert (i|j) >= 0 ; // both of them are nonnegative
E dummy = elements[i];
elements[i] = elements[j];
elements[j] = dummy;
}
private void ensureCapacity(int i) {
elements = Arrays.copyOf(elements,i);
}
public static void main(String... args){
Integer[] ints = new Integer[]{34,12,5,6,12,123,6,3,1,23,534,33,33,33,12,453,23,21};
PQ<Integer> pq= new MinHeapPQ<>();
for(int i : ints) pq.insert(i);
for(int i = pq.size() ; i >0 ;i--)
System.out.println(pq.removeMin());
pq= new MinHeapPQ< >(Arrays.asList(ints));
for(int i = pq.size() ; i >0 ;i--)
System.out.println(pq.removeMin());
}
}
以上是关于java 基于堆的最小优先级队列实现i java。的主要内容,如果未能解决你的问题,请参考以下文章