本文来源于《编程珠玑 第二版》第一章
位图和位向量表示:
用20位表示集合{2,3,5,6,10,13,19}为:01101100010010000010
电话号码排序问题:
输入:一个文件,有n个整数,没个整数要小于n,无重复
输出:以升序排序文件
约束:可用内存1MB,时限10s
算法:
//phase 1: initialize set to empty
for i=[0,n)
bit[i]=0;
//phase 2: insert present elements into the set
for each i in the input file
bit[i]=1
//phase 3: write sorted output
for i=[0,n)
if bit[i]==1
write i on the output file
自带源代码如下:
/* Copyright (C) 1999 Lucent Technologies */
/* From 'Programming Pearls' by Jon Bentley */
/* bitsort.c -- bitmap sort from Column 1
* Sort distinct integers in the range [0..N-1]
*/
#include <stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];
void set(int i) { a[i>>SHIFT] |= (1<<(i & MASK)); }
void clr(int i) { a[i>>SHIFT] &= ~(1<<(i & MASK)); }
int test(int i){ return a[i>>SHIFT] & (1<<(i & MASK)); }
int main()
{ int i;
for (i = 0; i < N; i++)
clr(i);
/* Replace above 2 lines with below 3 for word-parallel init
int top = 1 + N/BITSPERWORD;
for (i = 0; i < top; i++)
a[i] = 0;
*/
while (scanf("%d", &i) != EOF)
set(i);
for (i = 0; i < N; i++)
if (test(i))
printf("%d/n", i);
return 0;
}