基础思想: 线性排序,数组下标 表示元素的值,遍历数组即可得到有序的数列;
#include<iostream>
#include<vector>
using namespace std;
//桶排序 时间复杂度 O(x * n)
/*
实现线性排序,遍历取得数列中元素的最大值max,申请大小为max的内存空间buf,然后数列中的元素的值-1,
对应着buf中的下标;
*/
void my_swap(int& first, int& second)
{
int tmp = first;
first = second;
second = tmp;
}
void BucketSort(vector<int>& vec)
{
if (vec.empty()) return;
int max = INT_MIN;
//获取数列中的最大值
for (auto val : vec)
{
if (val > max) max = val;
}
//申请空间大小为max 的数组
int* pBuf = new int[max];
memset(pBuf, 0, max*sizeof(int));//初始化为0
//数列中各数值对应的下标
for (auto val : vec)
pBuf[val-1]++;
//遍历pBuf,大于0,表示是vec中的元素
for (int i = 0,j=0; i < max; i++)
{
if (pBuf[i] > 0) vec[j++] = i + 1;
}
}
int main()
{
vector<int> arr = { 12,5,9,34,3,97,63,23,53,87,120,11,77 };
cout << "raw val is:\n";
for (auto i : arr)
cout << i << "\t";
cout << endl;
BucketSort(arr);
cout << "BucketSort val is:\n";
for (auto i : arr)
cout << i << "\t";
cout << endl;
system("pause");
return 0;
}
输出: