堆排序算法(Java实现)

将待排序的序列构造成一个大顶堆(从大到小排要构造成小顶堆)。此时,整个序列的最大值就是堆顶的根节点,将他和末尾元素交换,然后将剩余的length-1个节点序列重新构造成新的堆。重复执行,便能得到一个有序序列。

 1 package sort;
 2 
 3 public class HeapSort {
 4     static void heapSort(int []a,int len){
 5         int i;
 6         for(i=len/2;i>=0;i--){ /*把a[]构造成一个大顶堆*/
 7             HeapAdjust(a,i,len);
 8         }
 9         for(i=len;i>0;i--){
10             swap(a,0,i); /*交换堆顶最大元素和堆尾最小元素*/
11             HeapAdjust(a,0,i-1);  /*把交换后的堆a[0,i-1],再次构造成大顶顶,使堆顶元素为最大值*/
12         }
13     }
14     static void HeapAdjust(int []a,int start,int len){
15         int temp,j;
16         temp=a[start];
17         for(j=2*start;j<=len;j*=2){   /*从index最大的有孩子的节点开始筛选,堆排*/
18             if(j<len&&a[j]<a[j+1])    /*是index=j的元素为较大的元素*/
19                 j++;
20             if(temp>=a[j])
21                 break;
22             a[start]=a[j];            /*将较大元素赋值给父节点*/
23             start=j;
24         }
25         a[start]=temp;              
26     }
27     static void swap(int a[],int low,int high){
28         int temp=a[low];
29         a[low]=a[high];
30         a[high]=temp;
31     }
32     public static void main(String []args){
33         int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };
34         heapSort(b, b.length - 1);
35         for(int w:b)
36             System.out.print(" "+w);
37     }
38 }

 

转载于:https://www.cnblogs.com/codeLZC/p/10464273.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值