#include<iostream>
#include<iomanip>
#include<cmath>
#define BASE 10
using namespace std;
//桶中元素链表
typedef struct entry
{
int element;
struct entry *next;
}ENTRY;
//维护每个桶中元素数目,并且指向第一个元素
typedef struct buc
{
int size;
ENTRY *head;
}BUCKET;
//桶内数据使用插入排序
void insertSort(BUCKET &bucket, const int &element)
{
ENTRY *tmp = bucket.head;
ENTRY *en = (ENTRY*)malloc(sizeof(ENTRY));
en->element = element;
en->next = NULL;
if ((tmp == NULL) || (tmp->element > en->element))
{
en->next = tmp;
bucket.head = en;
bucket.size++;
}
else
{
while (tmp != NULL)
{
if ((tmp->next == NULL&&tmp->element <= en->element) || (tmp->element <= en->element&&tmp->next->element > en->element))
{
en->next = tmp->next;
tmp->next = en;
bucket.size++;
break;
}
tmp = tmp->next;
}
}
}
int hasha(int data)
{
return data / 11;
}
//使用插入排序将数据分别插入对应的桶中
void createBucket(BUCKET *buckets, int *data, int n)
{
for (int i = 0; i < n; i++)
{
int num = hasha(data[i]);
insertSort(buckets[num], data[i]);
}
}
//将以排序数据反向输入到数组中
void reverseEvaluation(BUCKET *buckets, int *data, int n)
{
int idx = 0;
for (int i = 0; i < n; i++)
{
if (buckets[i].size != 0)
{
ENTRY *en = buckets[i].head;
while (en != NULL)
{
data[idx++] = en->element;
en = en->next;
}
}
}
}
void bucketSort(int *data, int n)
{
//创建并初始化桶的头结点
BUCKET *buckets = (BUCKET*)malloc(sizeof(BUCKET)*n);
for (int i = 0; i < n; i++)
{
buckets[i].size = 0;
buckets[i].head = NULL;
}
//向桶中放数据
createBucket(buckets, data,n );
//将桶中数据反向输入到数组
reverseEvaluation(buckets, data, n);
//释放内存
free(buckets);
}
void main()
{
int arr[] = { 10, 20, 15, 17, 28, 32, 21, 41, 33, 11 };
int length = sizeof(arr) / sizeof(int);
for (int i = 0; i < length; i++)
cout << arr[i] << " ";
cout << endl;
bucketSort(arr, length);
for (int i = 0; i < length; i++)
cout << arr[i] << " ";
cout << endl;
system("pause");
}