桶排序要求待排序的元素必须是正整数,如果不是正整数,转换为正整数:
#pragma once
#include<vector>
#include<iostream>
using std::vector;
using std::cout;
using std::endl;
template<typename ElemType>
struct Node
{
ElemType data;
Node<ElemType>* next;
Node() :data{}, next{ nullptr } {}
Node(ElemType d, Node<ElemType>* n = nullptr)
{
data = d;
next = n;
}
};
template<typename ElemType>
void bucket_sort(vector<ElemType>& vec)
{
if (vec.empty())
return;
ElemType maxVal=vec[0];
for (auto&& v : vec)
if (maxVal < v)
maxVal = v;
Node<ElemType>* ptr = nullptr;
vector<Node<ElemType>*>arr(maxVal);
for (auto&& v : vec)
{
if (arr[v - 1] != nullptr)
{
ptr = arr[v - 1];
while (ptr != nullptr)
{
if (ptr->next == nullptr)
break;
ptr = ptr->next;
}
ptr->next = new Node<ElemType>(v);
}
else
arr[v - 1] = new Node<ElemType>(v);
}
//排序完成
cout << "\n排序完成:" << endl;
for (int i = 0; i < maxVal; i++)
{
if (arr[i] != nullptr)
{
ptr = arr[i];
while (ptr != nullptr)
{
cout << ptr->data << ",";
ptr = ptr->next;
}
cout << endl;
}
}
//释放堆内存
Node<ElemType>* tmp;
for (int i = 0; i < maxVal; i++)
{
if (arr[i] != nullptr)
{
ptr = arr[i];
tmp = ptr->next;
while (tmp != nullptr)
{
delete ptr;
ptr = tmp->next;
tmp = tmp->next;
}
delete ptr;
}
}
}
void test_bucket_sort()
{
vector<int> vec;
for (int i = 0; i < 100; i++)
vec.push_back(std::rand() % 30+1);
cout << "没有排序前:" << endl;
for (auto&& v : vec)
cout << v << ",";
cout << endl;
bucket_sort<int>(vec);
}