堆排序


题目描述

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

class Solution {
public:
    void Insert(int num)
    {
      // 若是偶数,先插进最小堆
        if((max.size()+min.size())%2==0)
        {
           if(max.size()>0&&num<max[0])
           {
               
               max.push_back(num);
               
              push_heap(max.begin(),max.end(),less<int>());
               num=max[0];
               pop_heap(max.begin(),max.end());
               max.pop_back();
               
           }
            min.push_back(num);
            push_heap(min.begin(),min.end(),greater<int>());
        }
        else{
             if(min.size()>0&&num>min[0])
           {
               
               min.push_back(num);
              
              push_heap(min.begin(),min.end(),greater<int>());
                  num=min[0];
               pop_heap(min.begin(),min.end(),greater<int>());
               min.pop_back();
           }
            max.push_back(num);
            push_heap(max.begin(),max.end(),less<int>());
            
        }
    }

    double GetMedian()
    {  int size=max.size()+min.size();
      if(size%2==0)
          return (max[0]+min[0])/2.0;
     else
         return min[0];
            
    }
  private:
    vector<int>max;
    vector<int>min;

};
std::make_heap将[start, end)范围进行 堆排序,默认使用less<int>, 即最大元素放在第一个。(大顶堆)

std::pop_heap将front(即第一个最大元素)移动到end的前部,同时将剩下的元素重新构造成(堆排序)一个新的heap。

std::push_heap对刚插入的(尾部)元素做堆排序

std::sort_heap将一个堆做排序,最终成为一个有序的系列,可以看到sort_heap时,必须先是一个堆(两个特性:1、最大元素在第一个 2、添加或者删除元素以对数时间),因此必须先做一次make_heap.

注意!!如果堆是最小堆,要加上less<int>。不管是make push pop



算法:对vector进行堆排序 


#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

 

int main () {

  int myints[] = {10,20,30,5,15};

  vector<int> v(myints,myints+5);

  vector<int>::iterator it;

 

  make_heap (v.begin(),v.end());

  cout << "initial max heap   : " << v.front() << endl;

 

  pop_heap (v.begin(),v.end()); v.pop_back();

  cout << "max heap after pop : " << v.front() << endl;

 

  v.push_back(99); push_heap (v.begin(),v.end());

  cout << "max heap after push: " << v.front() << endl;

 

  sort_heap (v.begin(),v.end());

 

  cout << "final sorted range :";

  for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];

 

  cout << endl;

 

  return 0;

} 


输出:

 







1

2

3

4 


initial max heap   : 30

max heap after pop : 20

max heap after push: 99

final sorted range : 5 10 15 20 99 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值