有10亿个浮点数,从中找出1万个最大的数。写一个高性能的算法
算法和数据结构
1.一个数组,大小10000,指针指向头尾部,称min和max
2.排序下(算法自选吧)
3.比min指针小的数字,忽略;大于max的,max指针移到min指针位置,min右移一步.介于两者之间的,max指针不动,min右移.
4.当min指针到达数组最右端(无论max指针是否是在这里),排序一下子,两指针回到原来位置
5.重复2-4步骤,直至完成
对于排序的时候,时间复杂度不可避免(但规模是10000的)
3,4插入时,插入的时间复杂度是o(1)吧,而且能处理的数据应远大于10000个
因此,这样应该比所选用的排序的算法更快
//
// File: top10000.cc
// Created by: cc <tireless-heart@163.com>
// Created on: Fri Feb 29 12:26:53 2008
//
#include < iostream >
#include < vector >
#include < list >
#include < iterator >
#include " top10000.h "
#include " Counter.h "
#include " FileRelated.h "
using namespace std;
const static int VECTOR_SIZE = 10000 ;
void top10000( void )
{
FileRelated f;
Counter<int> lengthForReadFile;
vector<double> vectorForRead(VECTOR_SIZE);
list<double> listForInsert(VECTOR_SIZE);
//1stStep:
f.ReadFile(vectorForRead.begin(),VECTOR_SIZE);
lengthForReadFile.Count(VECTOR_SIZE);
sort(vectorForRead.begin(),vectorForRead.end());
copy(vectorForRead.begin(),vectorForRead.end(),listForInsert.begin());
//2ndStep:
list<double>::iterator minPtr=listForInsert.begin();
list<double>::iterator maxPtr=listForInsert.end();
--maxPtr;//
while(lengthForReadFile.NotArrived(f.LENGTH))
{
//3rdStep:
f.ReadFile(vectorForRead.begin(),VECTOR_SIZE);
lengthForReadFile.Count(VECTOR_SIZE);
//4thStep:
for(vector<double>::iterator iter=vectorForRead.begin();
iter!=vectorForRead.end();
++iter)
{
if(*iter>=*maxPtr)
{
listForInsert.insert(listForInsert.end(),*iter);
++maxPtr;
listForInsert.erase(minPtr++);
}
else if(*iter>*minPtr)//*minPtr<*iter<*maxPtr
{
list<double>::iterator replacePtr=
find_if(listForInsert.begin(),listForInsert.end(),
bind2nd(greater_equal<double>(),*iter));
listForInsert.insert(replacePtr,*iter);//before replacePtr
listForInsert.erase(minPtr++);
}
}
}
//5thStep:
copy(listForInsert.begin(),listForInsert.end(),ostream_iterator<double>(cout," "));
}