1.问题
随机产生50个100以内的不重复的整数,设计位图排序算法进行排序。
2.设计思路
阶段1: 初始化一个空集合
for i=[0,n)
bit[i]=0
阶段2: 读入数据i,并设置bit[i]=1
for each i in the input file
bit[i]=1
阶段3: 输出排序的结果
for i=[0,n)
if bit[i]==1
write i on the output file
3.源代码
#include <stdio.h>
#include <stdlib.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 100
int a[1 + N / BITSPERWORD];
void clr(int i)
{a[i >> SHIFT] = (1 << (i & MASK));
}void set(int i)
{a[i >> SHIFT] |= (1 << (i & MASK));
}int test(int i)
{return (a[i >> SHIFT] & (1 << (i & MASK)));
}int main()
{FILE *fp;int temp; //临时变量int i;fp = fopen("num.txt", "w"); //写入数据if (fp == NULL){printf("open file failed.\n");return 0;}for(i = 0; i < N / 2; i++){temp = rand() % N;fprintf(fp, "%d ", temp);}fclose(fp);for(i = 0; i < N; i++){clr(i);}fp = fopen("num.txt", "r"); //读数据if (fp == NULL){printf("open file failed.\n");return 0;}while(fscanf(fp, "%d", &temp) != EOF){set(temp);}fclose(fp);for(i = 0; i < N; i++) //输出排序{if(test(i)){printf("%d ", i);}}return 0;
}
4.实验结果及分析
运行结果:0 2 3 4 5 11 12 16 18 21 22 24 26 27 31 33 34 35 36 38 41 42 45 47 53 58 61 62 63 64 67 68 69 71 73 78 81 82 91 92 94 95 99
(位图排序时间复杂度为o(n),要求数据不重复,用bit位进行位图排序,能节省空间。该运行结果为排好序的100以内的整数,且无重复。)