C语言实现bitmap,取两个数组的交集等操作
转自:http://blog.csdn.net/qibaoyuan/article/details/5914746
代码实现:通过mod操作将指定数 i 映射到bitmap[i/32]的第 i mod 32 (从0开始)位。
bitmap的基本操作:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define WORD 32 4 #define SHIFT 5 ////移动5个位,左移则相当于乘以32,右移相当于除以32取整 5 #define MASK 0x1F //16进制下的31 6 #define N 10000000 7 /* 8 * 置位函数——用"|"操作符,i&MASK相当于mod操作 9 * m mod n 运算,当n = 2的X次幂的时候,m mod n = m&(n-1) 10 */ 11 void set(int *bitmap, int i) { 12 bitmap[i >> SHIFT] |= (1 << (i & MASK)); 13 } 14 /* 清除位操作,用&~操作符 */ 15 void clear(int *bitmap, int i) { 16 bitmap[i >> SHIFT] &= ~(1 << (i & MASK)); 17 } 18 /* 测试位操作用&操作符 */ 19 int test(int *bitmap, int i) { 20 return bitmap[i >> SHIFT] & (1 << (i & MASK)); 21 }
排序:
1 void sort() { 2 int bitmap[1 + N / WORD]; 3 FILE *in = fopen("in.txt", "r"); 4 FILE *out = fopen("out.txt", "w"); 5 if (in == NULL || out == NULL) { 6 exit(-1); 7 } 8 int i = 0; 9 int m; 10 for (i = 0; i < N; i++) { 11 clear(bitmap, i); 12 } 13 while (!feof(in)) { 14 fscanf(in, "%d", &m); 15 printf("%d/n", m); 16 set(bitmap, m); 17 } 18 printf("abnother"); 19 for (i = 0; i < N; i++) { 20 if (test(bitmap, i)) { 21 printf("%d/n", i); 22 fprintf(out, "%d/n", i); 23 } 24 } 25 fclose(in); 26 fclose(out); 27 }
求交集:
1 //合并两个数组,去交集 2 void merge() { 3 int A[] = { 1, 3, 5, 7, 9, 435, 3454, 345543, 3453455 }; 4 int B[] = { 4, 5, 6, 8, 9, 435, 3454, 345543 }; 5 int bitmapA[1 + N / WORD]; 6 int bitmapB[1 + N / WORD]; 7 int i = 0; 8 int j = 0; 9 for (i = 0; i < N; i++) { 10 clear(bitmapA, i); 11 clear(bitmapB, i); 12 } 13 for (i = sizeof(A) / sizeof(*A) - 1; i >= 0; i--) { 14 set(bitmapA, *(A + i)); 15 } 16 for (j = sizeof(B) / sizeof(*B) - 1; j >= 0; j--) { 17 set(bitmapB, *(B + j)); 18 } 19 for (i = 0; i < N; i++) { 20 if (test(bitmapA, i) & test(bitmapB, i)) {//交集 21 printf("%d/n", i); 22 } 23 } 24 } 25 int main(void) { 26 //sort(); 27 merge(); 28 return EXIT_SUCCESS; 29 }