您的位置:首页 > 编程语言 > Java开发

堆排序

2017-04-01 16:21 183 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 堆排序 算法