# 桶排序程序

#include <iostream.h>
#include <iomanip.h>

// constant size must be defined as the array size for bucketSort to work
const int SIZE = 12;

void bucketSort( int [] );
void distributeElements( int [], int [][ SIZE ], int );
void collectElements( int [], int [][ SIZE ] );
int numberOfDigits( int [], int );
void zeroBucket( int [][ SIZE ] );

int main()
{
int array[ SIZE ] = { 19, 13, 5, 27, 1, 26, 31, 16, 2, 9, 11, 21 };

cout << "Array elements in original order:/n";

for ( int i = 0; i < SIZE; ++i )
cout << setw( 3 ) << array[ i ];

cout << '/n';
bucketSort( array );

cout << "/nArray elements in sorted order:/n";

for ( int j = 0; j < SIZE; ++j )
cout << setw( 3 ) << array[ j ];

cout << endl;
return 0;
}

// Perform the bucket sort algorithm
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 );

if ( i != totalDigits )
zeroBucket( bucket );  // set all bucket contents to zero
}
}

// Determine the number of digits in the largest number
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;
}

// Distribute elements into buckets based on specified digit
void distributeElements( int a[], int buckets[][ SIZE ], int digit )
{
int divisor = 10, bucketNumber, elementNumber;

for ( int i = 1; i < digit; ++i )   // determine the divisor
divisor *= 10;                 // used to get specific digit

for ( int k = 0; k < SIZE; ++k ) {
// bucketNumber example for hundreds digit:
// (1234 % 1000 - 1234 % 100) / 100 --> 2

bucketNumber = ( a[ k ] % divisor - a[ k ] %
( divisor / 10 ) ) / ( divisor / 10 );

// retrieve value in buckets[bucketNumber][0] to determine
// which element of the row to store a[i] in.

elementNumber = ++buckets[ bucketNumber ][ 0 ];
buckets[ bucketNumber ][ elementNumber ] = a[ k ];
}
}

// Return elements to original array
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 ];
}

// Set all buckets to zero
void zeroBucket( int buckets[][ SIZE ] )
{
for ( int i = 0; i < 10; ++i )
for ( int j = 0; j < SIZE; ++j )
buckets[ i ][ j ] = 0;
}

#### 桶排序(二维数组)

2014年07月11日 2KB 下载

#### 经典排序算法（9）——桶排序算法详解

2016-03-16 13:16:40

#### #算法#C/C++#排序--桶排序

2017-04-14 19:16:12

#### 算法（一）排序算法（桶排序、冒泡排序、快速排序）

2017-04-07 18:43:32

#### 算法学习-桶排序(Bucket Sort) C++实现

2014-07-25 23:51:53

#### 桶排序C＋＋实现

2015-08-24 10:54:28

#### 计数排序、桶排序python实现

2014-07-12 14:28:02

#### 【经典算法】:桶排序

2016-04-13 14:47:41

#### 图解排序算法：桶排序

2016-11-04 13:52:32

#### 排序算法十：桶排序

2015-09-29 09:56:11