桶排序

#include <iostream>
#include <iomanip>
using namespace std;

const int SIZE = 10;

void zeroBucket(int buckets[][SIZE]);
void bucketSort(int a[]);
int numberOfDigits(int b[], int arraySize);
void distributeElements(int a[], int buckets[][SIZE], int digit);
void collectElements(int a[], int buckets[][SIZE]);

int main()
{
    int array[SIZE];
    cout << "原数组:\n";
    srand(time(0));
    //随机生成数组值
    for (int i = 0; i<SIZE; ++i)
    {
        array[i] = rand() % 100;
        cout << setw(3) << array[i] << "\t";
    }
    cout << '\n';
    cout << "排序过程演示:\n";
    bucketSort(array);
    cout << "排序后数组:\n";
    for (int j = 0; j < SIZE; ++j)
    {
        cout << setw(3) << array[j] << "\t";
    }
    cout << endl; cin.get();

    system("pause");
    return 0;
}

// 桶排序算法
void bucketSort(int a[])
{
    int totalDigits, bucket[10][SIZE] = { 0 };
    //确定最大数的位数
    totalDigits = numberOfDigits(a, SIZE);
    for (int i = 1; i <= totalDigits; ++i) {
        distributeElements(a, bucket, i);
        collectElements(a, bucket);
        //将桶数组初始化为0
        if (i != totalDigits) 
            zeroBucket(bucket);
        for (int j = 0; j < SIZE; ++j)
        {
            cout << setw(3) << a[j] << "\t";
        }
        cout << endl;
    }
}
//确定单下标数组的最大数的位数
int numberOfDigits(int b[], int arraySize)
{
    int largest = b[0], digits = 0;
    for (int i = 1; i<arraySize; ++i)
        if (b[i]>largest)
            largest = b[i];
    while (largest != 0) {
        ++digits;
        largest /= 10;
    }
    return digits;
}
// 将单下标数组的每个值放到桶数组的行中
void distributeElements(int a[], int buckets[][SIZE], int digit)
{
    int divisor = 10, bucketNumber, elementNumber;
    for (int i = 1; i<digit; ++i)
        divisor *= 10;
    for (int k = 0; k<SIZE; ++k) {
        //求取第m维数字
        bucketNumber = (a[k] % divisor ) / (divisor / 10);
        //buckets[bucketNumber][0] 表示桶中的数字个数
        elementNumber = ++buckets[bucketNumber][0];
        //放入对应的桶中
        buckets[bucketNumber][elementNumber] = a[k];
    }
}
//将桶数组的值复制回原数组
void collectElements(int a[], int buckets[][SIZE])
{
    int subscript = 0;
    for (int i = 0; i<10; ++i)
        for (int j = 1; j <= buckets[i][0]; ++j)
            a[subscript++] = buckets[i][j];
}
//将桶数组初始化为0
void zeroBucket(int buckets[][SIZE])
{
    for (int i = 0; i<10; ++i)
        for (int j = 0; j<SIZE; ++j)
            buckets[i][j] = 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值