位图排序1000万的无序数(内存小于1M)
2015-06-29 17:29
239 查看
//时间复杂度O(n), 空间复杂度O(n)
#include <iostream> #include <bitset> #include <assert.h> #include <time.h> using namespace std; const int max_each_scan = 5000000; int main() { clock_t begin = clock(); bitset<max_each_scan> bit_map; bit_map.reset(); // open the file with the unsorted data FILE *fp_unsort_file = fopen("data.txt", "r"); assert(fp_unsort_file); int num; // the first time scan to sort the data between 0 - 4999999 while (fscanf(fp_unsort_file, "%d ", &num) != EOF) { if (num < max_each_scan) bit_map.set(num, 1); } FILE *fp_sort_file = fopen("sort.txt", "w"); assert(fp_sort_file); int i; // write the sorted data into file for (i = 0; i < max_each_scan; i++) { if (bit_map[i] == 1) fprintf(fp_sort_file, "%d ", i); } // the second time scan to sort the data between 5000000 - 9999999 int result = fseek(fp_unsort_file, 0, SEEK_SET); if (result) cout << "fseek failed!" << endl; else { bit_map.reset(); while (fscanf(fp_unsort_file, "%d ", &num) != EOF) { if (num >= max_each_scan && num < 10000000) { num -= max_each_scan; bit_map.set(num, 1); } } for (i = 0; i < max_each_scan; i++) { if (bit_map[i] == 1) fprintf(fp_sort_file, "%d ", i + max_each_scan); } } clock_t end = clock(); cout<<"用位图的方法,耗时:"<<endl; cout << (end - begin) / CLK_TCK << "s" << endl; fclose(fp_sort_file); fclose(fp_unsort_file); system("pause"); return 0; }
bitmap总结:
适用范围:可进行数据的快速查找,判重,删除,一般来说数据范围是int的10倍以下
基本原理及要点:使用bit数组来表示某些元素是否存在,比如8位电话号码
扩展:bloom filter可以看做是对bit-map的扩展
问题实例:
1)已知某个文件内包含一些电话号码,每个号码为8位数字,统计不同号码的个数。
8位最多99 999 999,大概需要99m个bit,大概10几m字节的内存即可。
2)2.5亿个整数中找出不重复的整数的个数,内存空间不足以容纳这2.5亿个整数。
将bit-map扩展一下,用2bit表示一个数即可,0表示未出现,1表示出现一次,2表示出现2次及以上。或者我们不用2bit来进行表示,我们用两个bit-map即可模拟实现这个2bit-map。
相关文章推荐
- 故事:小孩儿堆沙子需要架构吗?
- [LeetCode]Rectangle Area
- java ThreadLocal使用方法
- 华为机试—掷骰子游戏
- 广告基本知识-广告的有效性模型
- LVS使用 (推荐)
- MyEclipse10中文乱码
- 视频图像处理过程中的时间消耗问题
- 英文版本的SQL SERVER 2008在修改表的允许为空时,不能修改。
- js 页面使用iframe 父页面子页面互相操作
- Mybatis 框架文档 超详细笔记
- GRE填空解题技巧介绍
- 《雍正王朝》里的音乐
- ssh只读事务的管理
- 事件冒泡和事件捕获
- 利用mmap /dev/mem 读写Linux内存
- haproxy安装配置
- MFC不能多线程访问控件..
- GET 对比 POST
- x86和arm对于锁实现的差异