使用位图解决电话号码排序问题--编程珠玑学习笔记 第一章

本文来源于《编程珠玑 第二版》第一章

位图和位向量表示:

用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;
}

 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值