基数排序

#include <iostream>                                                                                                                 
#include <stdlib.h> 
#include <time.h> 
#include <cstring>

using namespace std;

void Print(unsigned int * _arr, int nums)
{
    for(int i=0; i<nums; i++)
    {   
        cout<<_arr[i]<<" ";
    }   
    cout<<endl;
}

int getdigit(unsigned int digit, unsigned int bit )
{
     int bits[5] = {0, 1, 10 , 100, 1000}; //bits[0] 没有用 占位使用
     return digit/bits[bit]%10;
}

int main()
{
    srand((unsigned)time(NULL)); 
    int nums = 1000;
    unsigned int * arr = new unsigned int[nums];
    unsigned int * bucket = new unsigned int[nums];
    memset(bucket, 0, nums);
    for(int i=0; i<nums; i++)
    {   
        arr[i] = rand()%10000;
    }   
   
    Print(arr, nums);
    int * counts = new int[10];
    memset(counts, 0, sizeof(int)*10);
    
    for(int j=1; j<=4; j++)
    {   
        for(int i=0; i<nums; i++)
        {   
            counts[getdigit(arr[i], j)]++;    
        }   
        for(int h=1; h<10; h++)
        {   
            counts[h] = counts[h] + counts[h-1];
        }   
    
        for(int i=0; i<nums; i++)
        {   
            unsigned int num =  arr[i] ;
            int bit = counts[getdigit( num , j ) ];
            bucket[ bit - 1] = arr[i];
            counts[ getdigit( arr[i], j ) ] -- ;    
        }   
    
        //一定要重新赋值,调试时因为没有重新赋值,导致越界
        memset(counts, 0, sizeof(int)*10);  
        for(int i=0; i<nums; i++)
        {   
            arr[i] = bucket[i];
        }   
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值