C++排序(6)——堆排序

#include <iostream>
#include <vector>
using namespace std;

void swap (int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

void Heap_Insert(vector <int> &num_s, int num)
{
    int Far = (num - 1) / 2;
    while (num_s[Far] < num_s[num])
    {
        swap(num_s[Far], num_s[num]);
        num = Far;
        Far = (Far - 1) / 2;
    }
}

void Heap_Ify(vector <int> &num_s, int Heap_num, int Heap_size)
{
    int Left = 2 * Heap_num + 1;
    while (Left < Heap_size)
    {
        int largest = (Left + 1 < Heap_size && num_s[Left + 1] > num_s[Left])? Left + 1 : Left;
        if (num_s[Heap_num] > num_s[largest])
            break;
        swap(num_s[Heap_num], num_s[largest]);
        Heap_num = largest;
        Left = 2 * Heap_num + 1;    
    }
}

void Heap_Sort(vector <int> &num_s)
{
    if(num_s.size() < 1)
        return ;
    //建立大根堆
    for(int i = 0; i < num_s.size(); i++)
        Heap_Insert(num_s, i);

    //最大值交换
    int Heap_size = num_s.size();
    while(Heap_size > 0)
    {
        swap(num_s[0], num_s[--Heap_size]);
        //调整大根堆
        Heap_Ify(num_s, 0, Heap_size);
    }
    
}

int main()
{
    int num;
    vector <int> num_s;

    while(cin >> num)
        num_s.push_back(num);
    cout << "the original data is: " << endl;
    for (int i = 0; i < num_s.size(); i++)
        cout << num_s[i] << ' ';
    
    Heap_Sort(num_s);
    
    cout << endl << "the Heap_Sort data is" << endl;
    for(int i = 0; i < num_s.size(); i++)
        cout << num_s[i] << ' ';
    system("pause");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值