堆排序,想必大家已经很熟悉,下面贴代码。
public class HeapSort {
public void heapSort(int[] a){
for(int i=a.length/2-1;i>=0;i--){
adjustHeap(a,i,a.length);//建堆
}
for(int i=a.length-1;i>0;i--){
swap(a, 0, i);//把最大元素放到最后,再次建堆时不参与
adjustHeap(a,0,i);//再次建堆
}
}
//调整成堆
public void adjustHeap(int[] a,int i,int length){
int child = 0;
int max;
//从开始元素,从上到下依次进行调整。
for(max=a[i];leftChild(i)<length;i=child){
child=leftChild(i);
if(child!=length-1 && a[child]<a[child+1]){
child++;
}
if(max<a[child]){
a[i]=a[child];
}
else
break;
}
a[i]=max;
}
//左孩子的下标
public int leftChild(int i){
return 2*i+1;
}
//把最大元素依次放到最后,就是个交换
public void swap(int a[],int start,int max){
int temp=0;
temp=a[start];
a[start]=a[max];
a[max]=temp;
}
//堆排序的测试
public static void main(String[] args){
int a[]={1,10,7,3,6,4,2,8};
HeapSort heapSort=new HeapSort();
heapSort.heapSort(a);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}
输出结果
1 2 3 4 6 7 8 10
代码很简单,不过堆排序的思想值得人深思。