位图算法的实现

位图算法数据的产生,共生成了80万个数据,排序大概花了仅仅800ms,鉴于位图算法的时间复杂度是线性增加的,故可以判定处理更大的数据也会有很好的性能


//产生数据的算法
#include <vector>
#include<fstream>
#include<iostream>
#include<time.h>
using namespace std;


std::vector<int> s;
std::vector<int>res;
int n=100000000;

int main()
{
<span style="white-space:pre">	</span>//产生数据
<span style="white-space:pre">	</span>for (int i = 0; i < n; i++)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>s.push_back(i);
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>//随机选取
<span style="white-space:pre">	</span>for(int i=0;i<0.7*n;i++)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>int  a = ((int)((double)rand() / RAND_MAX * n)+rand())%s.size();
<span style="white-space:pre">		</span>res.push_back(s[a]);
<span style="white-space:pre">		</span>std::vector<int>::iterator it = s.begin()+a;
<span style="white-space:pre">		</span>s.erase(it);
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>FILE *outFile = fopen("test.txt", "a");
<span style="white-space:pre">	</span>for (int i=0;i<res.size();i++)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>fprintf(outFile,"%d\n",res[i]);
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>fclose(outFile);
}


//数据排序的算法
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;


vector <int> nums;


//define of the bitMap
#define BITSPERWORDS 32                   //一个int数值的位数
#define SHIFT 5                                   //由于每一个int数有32位,左移5位即是除以32
#define MASK 0x1F                              //31
#define N 1000000                              //数据总量
int a[1+N/BITSPERWORDS];               

//设置位,|=进行位的异或,(i & MASK)相当于mod操作,然后对1进行左移余数位(最小0,最大31)的操作
void set(int i)
{
     a[i>>SHIFT] |= (1<<(i & MASK));
}
//清楚位,&=进行位的操作,~(1<<(i & MASK))是数值对应的位置为0 然后进行&操作,即可清零
void clr(int i)
{
     a[i>>SHIFT] &= ~(1<<(i & MASK));
}
//测试,测试对应的int里位的位置是否为1。
int test(int i)
{
     return a[i>>SHIFT] & (1<<(i & MASK));
}

int main()
{


fstream fin("test.txt");  //打开文件
    string ReadLine;
int a ;
    while(getline(fin,ReadLine))  //逐行读取,直到结束
    {
sscanf(ReadLine.c_str(),"%d",&a);
nums.push_back(a);
    } 
    fin.close();


clock_t start = clock();
for(int i=0;i<N;i++)
clr(i);
for(int i=0;i<nums.size();i++)
set(nums[i]);




FILE *outFile = fopen("result.txt", "a");

for (int i=0;i<N;i++)
{
if(test(i))
fprintf(outFile,"%d\n",i);
}
clock_t duration = clock() - start;
fprintf(outFile,"%d ",duration/1000);
fclose(outFile);




}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值