计数排序
计数排序适用于数组中存储数的数据范围很小的情况下,时间空间复杂度都是 O ( n + k ) O(n + k) O(n+k)
- 将每个数字对应的个数存放在map中
- 遍历整个数字的范围,将每一个数字放回原数组mp[i]个。
代码
vector<int> sortArray(vector<int>& nums) {
unordered_map<int, int>mp;
for (int num:nums) {
mp[num]++;
}
int k = 0;
for (int i = -50000; i < 50000; i++) {
while(mp[i]) {
nums[k++] = i;
mp[i]--;
}
}
return nums;
}
桶排序
时间复杂度O(n), 空间复杂度O(M + N), 是计数排序的一个变种
- 使用映射函数进行建桶
- 将数据分别放入桶中
- 收集桶中的数据
#include<iterator>
#include<iostream>
#include<vector>
using namespace std;
const int BUCKET_NUM = 10;
struct ListNode{
explicit ListNode(int i=0):mData(i),mNext(NULL){}
ListNode* mNext;
int mData;
};
ListNode* insert(ListNode* head,int val){
ListNode dummyNode;
ListNode *newNode = new ListNode(val);
ListNode *pre,*curr;
dummyNode.mNext = head;
pre = &dummyNode;
curr = head;
while(NULL!=curr && curr->mData<=val){
pre = curr;
curr = curr->mNext;
}
newNode->mNext = curr;
pre->mNext = newNode;
return dummyNode.mNext;
}
ListNode* Merge(ListNode *head1,ListNode *head2){
ListNode dummyNode;
ListNode *dummy = &dummyNode;
while(NULL!=head1 && NULL!=head2){
if(head1->mData <= head2->mData){
dummy->mNext = head1;
head1 = head1->mNext;
}else{
dummy->mNext = head2;
head2 = head2->mNext;
}
dummy = dummy->mNext;
}
if(NULL!=head1) dummy->mNext = head1;
if(NULL!=head2) dummy->mNext = head2;
return dummyNode.mNext;
}
void BucketSort(int n,int arr[]){
vector<ListNode*> buckets(BUCKET_NUM,(ListNode*)(0));
for(int i=0;i<n;++i){
int index = arr[i]/BUCKET_NUM;
ListNode *head = buckets.at(index);
buckets.at(index) = insert(head,arr[i]);
}
ListNode *head = buckets.at(0);
for(int i=1;i<BUCKET_NUM;++i){
head = Merge(head,buckets.at(i));
}
for(int i=0;i<n;++i){
arr[i] = head->mData;
head = head->mNext;
}
}
参考文章
桶排序的详细讲解推荐桶排序这篇文章,本文桶排序也是参考了这篇文章。