经典排序之堆排序

来源:互联网 发布:数据共享交换平台 编辑:程序博客网 时间:2024/06/14 03:46
堆排序,想必大家已经很熟悉,下面贴代码。
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   

代码很简单,不过堆排序的思想值得人深思。

0 0
原创粉丝点击