要知道数据范围,然后定划分多少个区间,暂时不支持负数?
template<class T>
void my_printAry(T* a, int len) {
if (a == nullptr || !len)return;
for (int i = 0; i < len; i++)cout << a[i] << " "; cout << endl;
}
template<class T,int NUM>//分成NUM个区间,NUM>MAX/NUM,是严格大于,数据范围0-MAX
class bucketSort {
template<class T>
struct LinkNode
{
T _data;
LinkNode<T>* _next;
LinkNode(T data = 0) :_data(data), _next(nullptr) {}
};
typedef LinkNode<T> LNode;
LNode** _bucket;
public:
bucketSort() :_bucket(new LNode* [NUM]) {
for (int i = 0; i < NUM;i++) {
_bucket[i] = new LNode;//有头结点
}
}
~bucketSort(){
LNode* temp, *link;
for (int i = 0; i < NUM; i++) {
link = _bucket[i];
while (link != nullptr) {
temp = link;
link = link->_next;
delete temp;
}
}
}
void Sort(T* a, int len) {
int index;
for (int i = 0; i < len; i++){
index = a[i] / NUM;
if (index >= NUM || index < 0)continue;
insert(a[i], _bucket[index]);
}
for (int i = 1; i < NUM; i++)merge(_bucket[0], _bucket[i]);
LNode* temp = _bucket[0]->_next,*temp2= _bucket[0]->_next;
//while (temp2) { cout << temp2->_data<<","; temp2 = temp2->_next; }
for (int i = 0; i < len; i++) {//排序结果复制到原数组
//if (temp)break;
a[i] = temp->_data;
temp = temp->_next;
}
}
private:
void insert(T e, LNode* link) {
LNode* node = link;
//int index = e / NUM;//确定元素插入区间
while (node->_next && e >= node->_next->_data) {//遍历插入/排序
node = node->_next;
}
LNode* temp = new LNode(e);
temp->_next = node->_next;
node->_next = temp;
}
void merge(LNode* link1, LNode* link2) {
LNode* node = link2->_next;
while (node != nullptr) {
insert(node->_data, link1);
node = node->_next;
}
}
};
void test02() {
//sizeof(a) / sizeof(*a)
int a3[] = { 49,38,65,97,76,13,27,49 };
int a7[] = { 15,1,2,3,5,8,4,9,6,7 };
int a2[] = { 1,2,3,4,5,7,8,9,10,6 };
int a4[] = { 1,2,3,4,5,7,8,9,10,6 };
int a6[] = { 8,3,6,4,2,1,5,7,9,10,12,11 };
int a9[] = { 16,9,20,15,3,18,13,2,17,10,5,7,11,12,6,1,19,4,8,14 };
int a8[] = { 53,17,78,9,45,65,87,32 };
int a5[] = { 53, 3, 542, 748, 14, 214, 154, 63, 616 };
int a10[] = { 20,30,40,50,70,31,19,60 };
int a[] = { 4,68,60,1,54,57,50,69,76,94,70,18,2,5,36,96,80,63,84,19,17,64,46,83,15,74,58,81,75,49,62,39,16,51,30,65,21,53,44,26 };
//qsort(a, sizeof(a) / sizeof(*a), sizeof(*a), [](const void* a, const void* b)->int {return *(int*)a - *(int*)b; });
//my_printAry(a, sizeof(a) / sizeof(*a));
bucketSort<int, 11> bs; bs.Sort(a, sizeof(a) / sizeof(*a));
my_printAry(a, sizeof(a) / sizeof(*a));
}