位向量实现1000万无重复整数的排序

本文介绍了两种位集合排序算法的实现方法,一种是基于数组和位操作的传统方式,另一种是利用STL中的bitset进行实现。这两种方法都能有效地完成对整数集合的排序,并通过实例展示了具体的使用过程。

原书代码如下:

#include <iostream>
#include <math.h>
#include <time.h>

#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F

#define  M 100
#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 myRand()//产生一个0~N之间的随机数
{
    int num;
    num = rand()%N;
    return num;
}

int main()
{
    int i;
    int bitsort[M];
    for (i=0;i<N;i++)        
        clr(i);

//     while( scanf("%d",&i) != EOF )
//         set(i);

    srand((unsigned)time(NULL));
    printf("The original items of array[%d] are:\n",M);

    for (int j=0;j<M;j++)
    {
        bitsort[j] = myRand();
        printf(" %d",bitsort[j]);
        set(bitsort[j]);
    }
    printf("\n");

    printf("The sorted items of array[%d] are:\n",M);
    for (i=0;i<N;i++)
    {
        if (test(i))
        {
            printf(" %d",i);
        }
    }
    printf("\n");

    return 0;
}

另外,在STL中也有相应函数,示例代码如下(师弟提供)

#include <bitset>
const int iMaximumValue=99, iMinimumValue=0;

void BitSetSort(int *piArray, size_t uiCount){
    std::bitset<iMaximumValue-iMinimumValue+1> bsSort;
    for(size_t uiIndex=0; uiIndex<uiCount; uiIndex++){
        bsSort.set(static_cast<size_t>(piArray[uiIndex]-iMinimumValue));
    }
    for(size_t uiIndex=0; uiIndex<bsSort.size(); uiIndex++){
        if(bsSort.test(uiIndex)){
            *piArray=static_cast<int>(iMinimumValue+uiIndex);
            piArray++;
        }
    }
}

int wmain(int argc, wchar_t **argv, wchar_t envp){
    int ai[20]={
        5, 35, 4, 78, 22,
        48, 75, 3, 0, 58,
        33, 64, 79, 21, 11,
        6, 77, 20, 9, 10
    };
    BitSetSort(ai, 20);
    for(int iIndex=0; iIndex<20; iIndex++){
        std::wcout<<ai[iIndex]<<L' ';
    }
    return EXIT_SUCCESS;
}

 

转载于:https://www.cnblogs.com/xiaowenchao/archive/2013/04/25/3041991.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值