本文主要用java实现了简单的堆排序算法。
package cheng.guang.bing.algorithms;
/**
* 这是一个实现最大堆的数据结构程序
* @author Cheng Guangbing
* @date 2015.09.15
*
*/
public class HeapSort {
private Heap hp=null;
private class Heap {
int[] a=null;
int heapSize;
public Heap(int [] a){
this.a=a;
}
public int parent(int i){
return (i+1)/2;
}
public int left(int i){
return 2*(i+1);
}
public int right(int i){
return 2*(i+1)+1;
}
public String toString(){
StringBuilder sbBuilder = new StringBuilder();
for(int temp: a){
sbBuilder.append(temp);
sbBuilder.append(" ");
}
return sbBuilder.toString();
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a=new int[]{4,1,3,2,16,9,10,14,8,7};
HeapSort hs=new HeapSort(a);
hs.buildMaxHeap();
System.out.println("建的堆为: "+hs);
hs.heapSort();
System.out.println("经过堆排序的序列为:"+hs);
}
/**
* maxHeapify 用于维护最大堆的性质
* @param i 操作的节点
*/
public void maxHeapify(int i){
int l,r,largest,temp;
l=hp.left(i);
r=hp.right(i);
if(l<=hp.heapSize&&hp.a[l-1]>hp.a[i]){
largest=l-1;
}else largest=i;
if(r<=hp.heapSize&&hp.a[r-1]>hp.a[largest]){
largest=r-1;
}
if(largest!=i){
temp=hp.a[i];
hp.a[i]=hp.a[largest];
hp.a[largest]=temp;
maxHeapify(largest);
}
}
/**
* buildMaxHeap 自底向上的建堆过程
*/
public void buildMaxHeap(){
hp.heapSize=hp.a.length;
for(int temp=hp.a.length/2-1;temp>=0;temp-- ){
maxHeapify(temp);
}
}
public HeapSort(int[] a){
Heap newHeap=new Heap(a);
this.hp=newHeap;
}
/**
* heapSort 堆排序算法
*/
public void heapSort(){
int temp;
buildMaxHeap();
for(int i=hp.a.length-1;i>=1;i--){
temp=hp.a[0];
hp.a[0]=hp.a[i];
hp.a[i]=temp;
hp.heapSize=hp.heapSize-1;
maxHeapify(0);
}
}
public String toString(){
StringBuilder sbBuilder = new StringBuilder(" [ ");
sbBuilder.append(hp);
sbBuilder.append(" ] ");
return sbBuilder.toString();
}
}
运行结果:
建的堆为: [ 16 14 10 8 7 9 3 2 4 1 ]
经过堆排序的序列为: [ 1 2 3 4 7 8 9 10 14 16 ]