堆排序的Java实现

 本文主要用java实现了简单的堆排序算法。
package cheng.guang.bing.algorithms;

/**
 * 这是一个实现最大堆的数据结构程序
 * @author Cheng Guangbing
 * @date 2015.09.15
 * 
 */

public class HeapSort {


    //定义一个空堆
    private Heap hp=null;

    private class Heap {
        int[] a=null;
        int heapSize;
        public Heap(int [] a){
            this.a=a;
        }
        public int parent(int i){
            return (i+1)/2;
            }
        public int left(int i){
            return 2*(i+1);
        }
        public int right(int i){
            return 2*(i+1)+1;
        }

        public String toString(){
            StringBuilder sbBuilder = new StringBuilder();  
            for(int temp: a){
                 sbBuilder.append(temp);  
                 sbBuilder.append(" ");  
            }
            return sbBuilder.toString();
        }

    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a=new int[]{4,1,3,2,16,9,10,14,8,7};
        HeapSort hs=new HeapSort(a);
        hs.buildMaxHeap();
        System.out.println("建的堆为: "+hs);
        hs.heapSort();
        System.out.println("经过堆排序的序列为:"+hs);


    }

/**
 * maxHeapify 用于维护最大堆的性质
 * @param i 操作的节点
 */
public void maxHeapify(int i){
    int l,r,largest,temp;
    l=hp.left(i);
    r=hp.right(i);
    if(l<=hp.heapSize&&hp.a[l-1]>hp.a[i]){
        largest=l-1;
    }else largest=i;
    if(r<=hp.heapSize&&hp.a[r-1]>hp.a[largest]){
        largest=r-1;
    }
    if(largest!=i){
        temp=hp.a[i];
        hp.a[i]=hp.a[largest];
        hp.a[largest]=temp;
        maxHeapify(largest);
    }

}
/**
 * buildMaxHeap 自底向上的建堆过程
 */
public void buildMaxHeap(){
    hp.heapSize=hp.a.length;
    for(int temp=hp.a.length/2-1;temp>=0;temp-- ){
        maxHeapify(temp);   
    }
}
public HeapSort(int[] a){
    Heap newHeap=new Heap(a);
    this.hp=newHeap;
}

/**
 * heapSort 堆排序算法
 */
public void heapSort(){
    int temp;
    buildMaxHeap();
    for(int i=hp.a.length-1;i>=1;i--){
        temp=hp.a[0];
        hp.a[0]=hp.a[i];
        hp.a[i]=temp;
        hp.heapSize=hp.heapSize-1;
        maxHeapify(0);
    }   
}
public String toString(){
    StringBuilder sbBuilder = new StringBuilder(" [ "); 
    sbBuilder.append(hp);
    sbBuilder.append(" ] ");
    return sbBuilder.toString();
}

}

运行结果:

建的堆为:  [ 16 14 10 8 7 9 3 2 4 1  ] 
经过堆排序的序列为: [ 1 2 3 4 7 8 9 10 14 16  ] 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值