您的位置:首页 > 其它

经典排序之堆排序

2014-10-04 21:19 274 查看
堆排序,想必大家已经很熟悉,下面贴代码。
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


代码很简单,不过堆排序的思想值得人深思。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: