c++之树型排序

1.图形原理

2.代码(注释已经尽量写在文中)

#include<bits/stdc++.h>
using namespace std;

#define Left(i)      (2*(i)-2*n)
#define Right(i)   (2*(i)-2*n+1)
#define Father(i)  (n+(i)/2)
//#define Brother(i)  ((i)&1?(i)-1:(i)+1)
#define Root          (2*n-2)
#define min(a,b)      (a)<(b)?(a):(b)
#define INF_VALUE  0x3FFFFFF //(是所能表示的最大值)

//树形排序:从小到大
template<class T>
void treeSort(T* a, int n)
{
    T* t = new T(2*n-1);   
    memcpy(t, a, sizeof(T)*n); // 类似于for循环,会更快一些
 
     //第1轮选择
    for(int i=n; i<=Root; i++) // 循环完毕后得到最小值
    {
        t[i]= min(t[Left(i)],t[Right(i)]);   
        a[0]=t[Root];  
    }
     //第2轮至第n轮选择
     for(int k=1; k<=n-1; k++) 
     {       // 将上一轮的最小值修改为无穷大INF_VALUE。
         // 沿着等于t[Root]的分枝向下直到叶结点t[sel]=t[Root]
          int sel=Root;
          int left=Left(sel);
          while(left>=0) // 判断sel是否为叶节点
          {   
              sel = (t[sel]==t[left]) ? left : (left+1); // 一直反复循环反复循环,与root有关的都要记下来。
               left=Left(sel);
          } 
          t[sel]=INF_VALUE;    //找到最后的根节点,然后命为root。
  
          // 本轮选择:从叶往根从t[sel]往t[Root]选择最小值
          sel=Father(sel);
          while(sel<=Root)
          {   
            t[sel] = min(t[Left(sel)],t[Right(sel)]);
               sel = Father(sel);
          }
          a[k]=t[Root];
     }
     free(t);
}

int main()
{
    int a[10]={0,45,723,23,3,45,5,8,9,12345};
 
    treeSort(a, 10);
     for(int i=0; i<10; i++)
          cout<<a[i]<<" ";
     return 1;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值