有10亿个浮点数,从中找出1万个最大的数。



有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," "));
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值