Life is Good.

Enhance Tech and English
随笔 - 65, 文章 - 20, 评论 - 21, 引用 - 0
数据加载中……

10亿个浮点数,求出其中最大的10000个.


#include 
"stdafx.h"
#include 
<vector>
#include 
<iostream>
#include 
<algorithm>
#include 
<functional> // for greater<>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  vector
<float> bigs(10000,0);
  vector
<float>::iterator it;

  
// Init vector data
  for (it = bigs.begin(); it != bigs.end(); it++)
  {
    
*it = (float)rand()/7// random values;
  }

  cout 
<< bigs.size() << endl;

  make_heap(bigs.begin(),bigs.end(), greater
<float>()); // The first one is the smallest one!

  
float ff;
  
for (int i = 0; i < 1000000000; i++)
  {
    ff 
= (float) rand() / 7;
    
if (ff > bigs.front()) // replace the first one ?
    {
      
// set the smallest one to the end!
      pop_heap(bigs.begin(), bigs.end(), greater<float>()); 

      
// remove the last/smallest one
      bigs.pop_back(); 

      
// add to the last one
      bigs.push_back(ff); 

      
// mask heap again, the first one is still the smallest one
      push_heap(bigs.begin(),bigs.end(),greater<float>());
    }
  }

  
// sort by ascent
  sort_heap(bigs.begin(), bigs.end(), greater<float>()); 

  
// sort by descent
  
//sort_heap(bigs.begin(), bigs.end()); 
  
//sort_heap(bigs.begin(), bigs.end(), less<float>()); 

  
return 0;
}

posted on 2011-06-02 16:51 Mike Song 阅读(806) 评论(0)  编辑 收藏 引用 所属分类: C/C++面试题目


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理