基於堆的優先佇列和堆排序
阿新 • • 發佈:2019-01-24
- public class MaxPQ<Key extends Comparable<key>>{
- private Key[] pq;
- private int N = 0;
- pulbic MaxPQ(int maxN){
- //值儲存在pq[1...N]中,pq[0]不適用,所以陣列的長度為maxN+1
- pq = (Key[]) new Comparable[maxN+1];
- }
- public boolean isEmpty(){
- return N==0;
- }
- public int size(){
- return N;
- }
- public void insert(Key v){
- pq[++N] = v;
- swim(N);
- }
- public Key delMax(){
- Key max = pq[1];
- exch(q,N--);
- pq[N+1]=null;
- sink(1);
- return max;
- }
- //上浮
- private void swim(int n){
- while(n>1&&less(n/2,n)){
- exch(n/2,n);
- n=n/2;
- }
- }
- //下沉
- private void sink(int k){
- while(k*2<=N){
- int j = k*2;
- if(less(j,j+1)) j++;
- if(!less(k,j)) break;
- exch(k,j);
- k=j;
- }
- }
- private boolean less(int i,int j){
- //return pq[i]<pq[j]?true:false;
- return pq[i].compareTo(pq[j])<0;
- }
- private void exch(int i,int j){
- Comparable temp;
- temp = pq[i];
- pq[i] = pq[j];
- pq[j] = temp;
- }
- }