堆排序

来源:互联网 发布:淘宝a店是什么店 编辑:程序博客网 时间:2024/05/19 07:11
public class Heapsort {
    //找到左孩子
    private static int leftChild(int i){
        return 2*i+1;
    }
    private static <AnyType extends Comparable<? super AnyType>>
    void percDown(AnyType[] a ,int i,int n){
        int child;
        AnyType tmp;
        for(tmp=a[i];leftChild(i)<n;i=child){
            child=leftChild(i);
            if(child!=n-1&&a[child].compareTo(a[child+1])<0)
                child++;
            if(tmp.compareTo(a[child])<0)
                a[i]=a[child];
            else
                break;
        }
        a[i]=tmp;
    }
    public static <AnyType extends Comparable<? super AnyType>>
    void heapsort(AnyType[] a){
        @SuppressWarnings("unchecked")
        //创建一个相同长度的数组
        AnyType[] b=(AnyType[])new Comparable[a.length];
        for(int i=a.length/2-1;i>=0;i--)
            percDown(a,i,a.length);//对于所有不是叶子节点的节点进行向下过滤
        for(int i=a.length-1;i>=0;i--)
        {
            AnyType f=swapReferences(a,0,i);//去除根节点,并把最后一个元素作为根节点值
            b[i]=f;
            percDown(a,0,i);//然后对根节点进行过滤
        }
        for(int i=0;i<a.length;i++){
            a[i]=b[i];
        }
    }
    private static <AnyType extends Comparable<? super AnyType>>
    AnyType swapReferences(AnyType[] a, int start,int end){
        AnyType result=a[start];
        a[start]=a[end];
        a[end]=result;
        return result;
    }

}


测试:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Integer[] nums=new Integer[]{1,5,1,6,2,7,3,5,2,8,3,4};
        //Shellsort.shellsort(nums);
        Heapsort.heapsort(nums);
        for(Integer num:nums){
            System.out.print(num+" ");
        }

效果:

1 1 2 2 3 3 4 5 5 6 7 8


0 0