1. 描述
计数排序是一个桶对应一个数值,而桶排序则是一个桶内有多个数值。桶内部进行插入或者其他的排序。最后再根据桶基数大小排序成最后的结果。
步骤
- 哈希分桶
- 根据哈希值将待排序值放入桶
- 各个桶内排序
- 将桶中的元素输出到输出值中
2. 源代码
#include <iostream>
struct bucketNode {
float v;
struct bucketNode *next;
};
int HashFunc(float v)
{
return (int) (v * 10);
}
void insert_val_and_sort(struct bucketNode **bucket, int idx, float insVal)
{
struct bucketNode *newNode = new struct bucketNode();
newNode->next = nullptr;
newNode->v = insVal;
struct bucketNode *head = bucket[idx];
if ( head == nullptr) {
bucket[idx] = newNode;
return ;
}
if ( head->v > insVal) {
newNode->next = head;
bucket[idx] = newNode;
return ;
}
struct bucketNode *nxt = head->next;
struct bucketNode *cur = head;
while ( nxt && nxt->v > insVal) {
cur = nxt;
nxt = nxt->next;
}
newNode->next = nxt;
cur->next = newNode;
}
void bucketSort(float toSort[], int sz, float res[])
{
struct bucketNode **bucket = new struct bucketNode *[10];
for ( int i = 0; i < sz; ++i) {
bucket[i] = nullptr;
}
for ( int i = 0; i < sz; ++i) {
int idx = HashFunc(toSort[i] );
insert_val_and_sort(bucket, idx, toSort[i] );
}
int cnt = 0;
for ( int i = 0; i < 10; ++i) {
struct bucketNode *cur = bucket[i];
while (cur) {
res[cnt++] = cur->v;
cur = cur->next;
}
}
}
int main (int argc, char *argv[])
{
float arr[10] = { 0.12,0.09,0.98, 0.77, 0.23,0.66,0.54, 0.18, 0.46, 0.33 };
float res[10] = {0};
int sz = 10;
bucketSort( arr, sz, res);
for ( int i = 0; i < sz; ++i)
std::cout << res[i] << " ";
return 0;
}
3. 理解
hash
+ insert_sort