JAVA演算法起步之堆排序執行個體_java

來源:互聯網
上載者:User

學習堆排序,首先需要明白堆的概念,堆是一個數組。可以近似當做完全二叉樹的數組儲存方式。但是跟他還有其他的性質,就是類似於二叉排序樹。有最大堆跟最小堆之分,最大堆是指根節點的值都大於子節點的值,而最小堆的是根節點的值小於其子節點的值。堆排序一般用的是最大堆,而最小堆可以構造優先隊列。堆裡面有一個方法是用來維護堆的性質,也就是我們下面代碼中的maxheap方法,這是維護最大堆性質的方法,第一個參數就是堆也就是數組,第二個參數是調整堆的具體節點位置,可能這個節點的值不符合最大堆的性質,那麼這個值得位置就作為參數,而size其實是堆內實際儲存的有效元素個數。可能數組的長度就是堆內實際儲存的元素個數,但是不一定所有的資料我們都需要進行構建最大堆。演算法導論中說的得到左子結點是2xi但是我們數組是從0開始計數的,所以左子結點就成了2xi+1,buildheap就是構建一個最大堆,我們去2分之長度的原因是,這些點的子節點都是葉子節點,所以我們通過從下向上進行排序來構建一個最大堆。保證了我們堆內所有節點都滿足最大堆性質。最後堆排序就是把第一個節點取出來,將剩下的節點再進行堆排序,再取出根節點。這樣保證我們每次取出都是最大值。

複製代碼 代碼如下:

public class HeapSort {
 private int getLeft(int i){
  return 2*i+1;
 }
 private int getRight(int i){
  return 2*i+2;
 }
 public void maxheap(int[] heap,int loc,int size){
  int l=getLeft(loc);
  int r=getRight(loc);
  int largest=loc;
  if(l<size&&heap[l]>heap[loc]){
   largest=l;
  }
  if (r<size&&heap[r]>heap[largest]) {
   largest=r;
  }
  if(largest!=loc){
   int cache=heap[loc];
   heap[loc]=heap[largest];
   heap[largest]=cache;
   maxheap(heap, largest, size);
  }
 }
 public void buildheap(int[] heap){
  for(int i=heap.length/2;i>=0;i--){
   maxheap(heap, i, heap.length);
  }
 }
 public void sort(int[] heap){
  buildheap(heap);
  for(int i=heap.length-1;i>1;i--){
   int cache=heap[0];
    heap[0]=heap[i];
    heap[i]=cache;
   maxheap(heap, 0,i );
  }
  int cache=heap[0];
   heap[0]=heap[1];
   heap[1]=cache;

 }

 public static void main(String[] args) {
  int[] heap=new int[]{4,1,5,3,7,12,65,7};
  HeapSort hs=new HeapSort();
  hs.sort(heap);
  for (int i = 0; i < heap.length; i++) {
   System.out.println(heap[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.