堆排序是幾種排序中比較難理解的一點,開始學資料結構的時候有些渾渾噩噩,原理沒搞清楚了就看代碼,越搞越糊塗,也越困,加之那時候大學,沒意識到良好的演算法基礎意味著什麼,所以直到快畢業基礎資料結構和演算法都是一塌糊塗,找工作時候才耐下性子看了下,如今工作一年了,面對著慘淡的工作環境和薪資,讓我有種學習的動力,如果你跟我一樣苦逼,那就抽時間好好打打基礎吧。
我是比較追求簡潔明了的那種,所以給出的代碼基本上是比較好理解的,因為難理解的我理解不了,也就沒辦法對照代碼看懂驗證或者是寫出來。理解堆排序一定要記得是用完全二叉樹的性質來對數組元素進行排序,是一種思想,而不是建一顆完全二叉樹排序。
廢話不多說,看下堆的定義(十本書基本一樣,這裡摘自wiki)
堆排序(Heapsort)是指利用堆這種資料結構所設計的一種排序演算法。堆是一個近似完全二叉樹的結構,並同時滿足堆性質:即子結點的索引值或索引總是小於(或者大於)它的父節點。wiki上面有很多很好的資料,如果有條件盡量看英文的,一般都能看懂,如果看了wiki後還不明白可以google,這些常用的演算法總會找到一個讓你能看懂的。
package com.mars.sort;public class HeapSortWiki { private void siftDown(int[] a, int start, int end){ int root = start; //child 孩子節點,swap 要交換的節點 int child, swap; //while root has at least one child while(root * 2 + 1 <= end){ child = root * 2 + 1; //初始將根節點作為需要交換的節點,如果根節點跟左右子節點 //比較後,swap == root則說明不需要調整,則表明該子樹 //是一個小根堆,無需調整 swap = root; //檢查根節點是否小於左子樹 if(a[swap] < a[child]){ swap = child; } //這裡有個技巧,如果左節點大於父節點,那麼這裡比較的是 //左右節點,否則是父節點和右節點比較 if(a[swap] < a[child + 1]){ swap = child + 1; } //檢查是否需要交換 swap == root說明已經是一個小堆了, //不需再做調整 if(swap != root){ int tmp = a[root]; a[root] = a[swap]; a[swap] = tmp; }else{//swap == root說明已經是一個小堆 return; } } } /** * 從樹的最底層檢查是否滿足堆的屬性 * @param a * @param count */ private void heapify(int[] a, int count){ //從最後一個父節點開始 int start = (count - 2) / 2; while(start >= 0){ //sift down the node at index start to //the proper place such that all nodes //below the start index are in heap order siftDown(a, start, count - 1); start -= 1; } } public void heapSort(int[] a, int count){ heapify(a, count); int end = count - 1; while(end > 0){ int tmp = a[end]; a[end] = a[0]; a[0] = tmp; end -= 1; heapify(a, end); } } public static void main(String[] args) { int a[] = {1, 0, 4, -1, 5, 2, 6, 9, 8, 7, 3}; new HeapSortWiki().heapSort(a, 11); for(int b : a){ System.out.print(b + " "); } }}
http://www.cnblogs.com/zabery/archive/2011/07/26/2117103.html
http://en.wikipedia.org/wiki/Heapsort