堆排序

条件:

1、完全二叉树(性质)

2、父节点大于子节点

 

比如

 

构建一个堆

 

 

子节点中最大值于父节点交换

 

从倒数第二次开始heapify

 

 

完全二叉树的性质

 

 

 

多个节点heapify

 

  5     > Created Time: 2019年09月16日 星期一 23时23分40秒

  6  ************************************************************************/

  7

  8 #include<stdio.h>

  9 void swap(int arr[], int  a, int b){

 10     int temp =arr[a];

 11     arr[a] = arr[b];

 12     arr[b] = temp;

 13 }

 14

 15 void heapify(int tree[], int n, int i){//堆化:满足堆的条件,

对第i节点堆化

 16     if(i >= n){

 17         return ;

 18     }

 19     int c1 = 2 * i + 1;//子节点,完全二叉树的性质

 20     int c2 = 2 * i + 2;

 21     int max = i;                                                                       

 22     if(c1 <n && tree[c1] > tree[max])

 23     {

 24         max = c1;

 25     }

 26     if(c2 < n && tree[c2] > tree[max])

 27     {

 28         max = c2;

 29     }

 30     if(max != i)

 31     {

 32         swap(tree,max,i);

 33         heapify(tree,n,max);

 34     }

 35 }

 36

 37 void build_heap(int tree[], int n){//多个节点堆化

 38     int last_node = n - 1;

 39     int parent = (last_node - 1) / 2;

 40     int i;

 41     for(i = parent;  i >= 0; i--){

 42         heapify(tree,n,i);

 43     }

 44 }

 45

 46 void heap_sort(int tree[], int n){//堆的排序

 47     build_heap(tree,n);

 48     int i;

 49     for(i = n - 1; i >= 0; i--){

 50         swap(tree,i,0);//把第一个节点于最后一个节点交换

 51         heapify(tree,i,0);

 52     }

 53 }

 54

 55 int main()

 56 {

 57     int arr[]={

 58         2,5,3,1,10,4

 59     };

 60     int n = 6;

 61 //  heapify(arr,n,0);

 62 //  build_heap(arr,n);

 63     heap_sort(arr,n);

 64     int i;

 65     for(i = 0; i < n; i++)

 66     {

 67         printf("%d\n",arr[i]);

 68     }

 69     return 0;

 70 }

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值