堆排序

/**

这边用最大二叉堆实现堆排序算法,熟悉一下建堆的过程

**/

#include <iostream>

using namespace std;

 

void  heapify(int nums [] ,int start ,int n)      //start是需要调整的最小的下标,n是最大的下标,需要调整的最大下标,可以取到下标

{

 

int l = start * 2 + 1;

int r = start * 2 +2;

int tem = start;

 

if(l <= n && nums[start] < nums [l])

   start = l;

if(r <= n &&nums [start] < nums [r])     //这边两个判断的作用是找出start以及他的子女中最大的一个值

    start = r;

if(start != tem)                                      //说明start位置变换过了,值比他的子女小,需要调整

{

         int max = nums[start];

nums[start] = nums [tem];

nums [tem] = max;

heapify(nums,start,n);

}   

}

 

void makeHeap(int nums[] ,int n)

{

    for(int i = n/2;i>=0;i--)

heapify(nums,i,n-1);

}

 

void  heapsort(int nums  [] ,int n)

{

 

makeHeap(nums,n);         

    for(int i = n-1 ; i > 0 ;i--)

{

        int tem = nums [i] ;                     //总是取得当前未排序数中的最大值

        nums[i] = nums [0];

        nums[0] = tem;

        heapify(nums,0,i-1);

}

}

 

int   main()

{

int nums [] = { 10,20,14,17,3,11,98,-14};

heapsort(nums,8);

for(int i = 0;i < 8; i++)

cout << nums [i] << "   " ;

cout << endl;

 

return 0;

}

 

 

做一个堆排序为下边的用二叉堆实现Dijkstra算法和prim算法热热身啊

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值