偶然在网站发现腾讯的一道面试题,在1亿个数字里面找前一百个最大数,然后深究发现位图排序算法。
不多说,直接上代码:
#include <iostream>
#include <ctime>
#include "windows.h"
using namespace std;
#ifndef WEITU1
#define WEITU1
#endif
//搜索temp是否在数组pIArray中
bool ExistInpIArray(int pIArray[],int k,int temp)
{
for(int i=0; i<k; ++i)
{
if(temp== pIArray[i])
return true;
}
return false;
}
void ProcessUnits(int pIArray[],int pIArrayNN[],int k,int n)
{
int i;
for(i=0; i<n; ++i)
{
if(ExistInpIArray(pIArray,k,i))
pIArrayNN[i]=1;
}
for(i=0; i<n; ++i)
{
if(pIArrayNN[i])
cout<<i<<ends;
}
}
void UpUnits(int *number,int *numberNN,int icount,int imax)
{
int i;
for (i = 0; i<icount; i++)
{
numberNN[number[i]] = 1;
}
for (i = 0; i<imax; i++)
{
if (numberNN[i])
{
cout<<i<<ends;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int icount,imax;
cout<<"please input icount:";
cin>>icount;
cout<<"please input imax:";
cin>>imax;
if (icount > imax)
{
cout<<"input error";
return 0;
}
srand((unsigned)time(NULL));
int *number = new int[icount];
memset(number,0,icount*sizeof(int));
int i;
for (i = 0;i<icount; i++)
{
number[i] = rand()%imax;
}
// for (i = 0; i<icount; i++)
// {
// cout<<number[i]<<",";
// if (0!=i && 0 == i%10)
// {
// cout<<"/n";
// }
// }
cout<<"/n__________________________________________________"<<endl;
DWORD64 iCurrent_time = GetTickCount();
#ifdef WEITU1
int *numberNN = new int[imax];
memset(numberNN,0,imax*sizeof(int));
UpUnits(number,numberNN,icount,imax);
delete []numberNN;
#endif
#ifdef WEITU2
int *numberNN = new int[imax];
memset(numberNN,0,imax*sizeof(int));
ProcessUnits(number,numberNN,icount,imax);
delete []numberNN;
#endif
#ifdef USUALLY
int itemp = 0;
for (i = 0; i<icount-1;i++)
{
for (int j = i+1;j<icount;j++)
{
if (number[i]>number[j])
{
itemp = number[i];
number[i] = number[j];
number[j] = itemp;
}
}
}
for (i = 0; i<icount; i++)
{
cout<<number[i]<<ends;
}
#endif
cout<<"/nexpend time = "<<GetTickCount()-iCurrent_time<<endl;
cout<<"/n/nEND"<<endl;
delete []number;
return 0;
}
CPU是core(TM)2 T5870,随机产生icount个数,大小在0-imax之间,定义了三个宏:WEITU1,WEITU2,USUALLY。
宏USUALLY示例了普通的排序算法,
宏WEITU2示例了我在网上找到的位图排序,
宏WEITU1示例了我在WEITU2之上改良了位图排序。
进行了三轮测试,每轮测试每种算法跑三编,并记录了算法所消耗的时间(毫秒)。
第一轮,icount = 1000,imax = 2000.
WEITU1跑三遍的消耗时间分别是:468, 452, 468
WEITU2跑三遍的消耗时间分别是:452, 515, 468
USUALLY跑三遍的消耗时间分别是:609, 609, 640
第二轮,icount = 10000,imax = 20000.
WEITU1跑三遍的消耗时间分别是:5258, 5367, 5319
WEITU2跑三遍的消耗时间分别是:6069, 5865, 6068
USUALLY跑三遍的消耗时间分别是:7223, 7145, 7410
第三轮,icount = 100000,imax = 200000.
WEITU1跑三遍的消耗时间分别是:21856, 21107, 21949
WEITU2跑三遍的消耗时间分别是:94334, 95772, 89248
USUALLY跑三遍的消耗时间分别是:108452, 105660, 104988
788




被折叠的 条评论
为什么被折叠?



