java資料結構—堆

來源:互聯網
上載者:User

1.  由於用數組來類比堆的資料存放比較方便,且數組0號位置作為哨兵

package com.jzm.HeapMap;public class Maxheap <T extends Comparable<? super T>>{    private T[] heap; // 存放堆 元素的數組    private int lastIndex; //最後一個元素的索引    private static final int default_capacity = 20;        public Maxheap(){     this(default_capacity);        }        public Maxheap(int size){        heap = (T[])new Comparable[size];    lastIndex = 0;        } //end constructor        public boolean isEmpty(){    return  lastIndex < 1;        }//判斷是否為空白        public void  doubleArray(){    int enlarge = heap.length*2;    T[] a = (T [])new Comparable[enlarge];    for(int i=1;i<=lastIndex;i++){     a[i] = heap[i];         }    heap = a;    }//擴大數組空間            public void add(T newEntry){    lastIndex++;    if (lastIndex >= heap.length) { doubleArray();}        int newIndex =  lastIndex;    int parentIndex = newIndex/2;    while(newIndex >1 && newEntry.compareTo(heap[parentIndex])>0){     heap[newIndex] = heap[parentIndex];     newIndex = parentIndex;     parentIndex = newIndex/2;     }//end while        heap[newIndex] =  newEntry;        }//end add              private void reheap(int rootIndex){          boolean done =  false;           T   orphanT = heap[rootIndex];      int  largerChildIndex = 2*rootIndex;            while(!done  && largerChildIndex <= lastIndex)      {                    int  leftChildIndex = largerChildIndex;       int  rightChildIndex =  leftChildIndex+1;            if(rightChildIndex <= lastIndex      &&heap[rightChildIndex].compareTo(heap[largerChildIndex])>0){       largerChildIndex = rightChildIndex;        }  //找到最大的孩子                      if(orphanT.compareTo(heap[largerChildIndex])<0){      heap[rootIndex] = heap[largerChildIndex];      rootIndex = largerChildIndex;      largerChildIndex = 2*rootIndex;                  }else{              done = true;            }            }//end while             heap[rootIndex] = orphanT;        }//end reheap                public T removeMax(){           T root = null;    if(!isEmpty()){    root    = heap[1];         //傳回值    heap[1] = heap[lastIndex]; //形成半堆    lastIndex--;               //堆的大小減1    reheap(1);         //轉化為堆    }//end if            return root;            } //end removeMax             public T getMax(){    T root = null;    if (!isEmpty()) {root = heap[1];}    return root;        }//end getMax 得到大頂堆頂數          public int getSize(){    return lastIndex;    }//得到堆的大小        public void clear(){        for(; lastIndex >= 0; lastIndex--){    heap[lastIndex]=null;        lastIndex = 0;        }    }//end clear 清空堆         public void display(){        for (int i = 1; i <=lastIndex; i++) {System.out.println(" "+heap[i]);}        }            public static void main(String[] args) { Maxheap<Integer> maxheap = new Maxheap<Integer>(); maxheap.add(1); maxheap.add(2); maxheap.add(5); maxheap.add(6); maxheap.add(3); maxheap.add(4); maxheap.display();  maxheap.removeMax(); System.out.println("---------------"); maxheap.display();  }  }

 

2.   堆排序

package com.jzm.HeapMap;public class HeapSort{ private static<T extends Comparable<? super T>> void reheap(T []heap,int rootIndex,int lastIndex){              boolean done =  false;               T   orphanT = heap[rootIndex];          int  largerChildIndex = 2*rootIndex;                while(!done  && largerChildIndex <= lastIndex)      {                    int  leftChildIndex =   largerChildIndex;       int  rightChildIndex =  leftChildIndex+1;            if(rightChildIndex <= lastIndex      &&heap[rightChildIndex].compareTo(heap[largerChildIndex])>0){       largerChildIndex = rightChildIndex;        }  //找到最大的孩子               if(orphanT.compareTo(heap[largerChildIndex])<0){      heap[rootIndex] = heap[largerChildIndex];      rootIndex = largerChildIndex;      largerChildIndex = 2*rootIndex;                  }else{              done = true;            }            }//end while          heap[rootIndex] = orphanT;        }//end reheap            private static <T extends Comparable<? super T>> void swap(T []a,int i,int j){     T t = a[i];     a[i]= a[j];     a[j] = t;        }       public  static<T extends Comparable<? super T>> void heapSort(T []array,int n){      //建立初始堆    for (int rootIndex = n/2-1; rootIndex >= 0; rootIndex--){             reheap(array,rootIndex,n-1);            for (int i = 0; i < array.length; i++) { System.out.print(" "+array[i]);  }             System.out.println("\n---------------------------");    }    swap(array,0,n-1);         for (int lastIndex =n-2; lastIndex>0 ; lastIndex--){     reheap(array, 0, lastIndex);     swap(array,0,lastIndex);}//end for        }//end heapSort    public static void main(String[] args) {     Integer [] a={20,40,30,10,90,70};     heapSort(a,a.length);        for (int i = 0; i < a.length; i++) {System.out.print(" "+a[i]); }}  }

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.