首页 > 编程语言 > 详细

java中的堆排序算法

时间:2020-04-16 09:44:58      阅读:54      评论:0      收藏:0      [点我收藏+]
public static void heapsort(int[] a)
    {
        int len = a.length;
        //构建堆
        for(int i = len / 2 - 1;i >= 0 ;i-- )
        {
            heapadjust(a,i,len - 1);
        }
        for(int j=len -1;j>0;j--)
        {
            int temp = a[0];
            a[0] = a[j];
            a[j] = temp;
            heapadjust(a,0,j-1);
        }
    }
    
    public static void heapadjust(int[] a,int pos,int len)
    {
        int child = 2 * pos + 1;
        int tmp = a[pos];
        while(child <= len)
        {
            if(child <len && a[child] < a[child + 1])
            {
                child ++;
            }
            if(a[child] >tmp)
            {
                a[pos] = a[child];
                pos = child;
                child = 2*pos + 1;
            }
            else 
            {
                break;
            }
        }
        a[pos] = tmp;
    }
    
    public static void main(String[] args) {
        int[] array = { 49, 38, 65, 97, 76, 13, 27, 50 };
        for(int i : array)
        {
            System.out.print(i + " ");
        }
        heapsort(array);
        System.out.println();
        for(int i = 0;i<array.length;i++)
        {
            System.out.print(array[i] + " " );
        }
    }

 

java中的堆排序算法

原文:https://www.cnblogs.com/suyun0702/p/12673457.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!