|
|
#include <stdio.h>
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
typedef struct node {
|
|
|
int key;
|
|
|
struct node *next;
|
|
|
}KeyNode;
|
|
|
|
|
|
void bucket_sort(int keys[], int size, int bucket_size) {
|
|
|
int i, j;
|
|
|
KeyNode **bucket_table = (KeyNode **)malloc(bucket_size * sizeof(KeyNode*));
|
|
|
for (i = 0; i < bucket_size; i++) {
|
|
|
bucket_table[i] = (KeyNode*)malloc(sizeof(KeyNode));
|
|
|
bucket_table[i]->key = 0;
|
|
|
bucket_table[i]->next = NULL;
|
|
|
}
|
|
|
for (j = 0; j < size; j++) {
|
|
|
KeyNode *node = (KeyNode *)malloc(sizeof(KeyNode));
|
|
|
node->key = keys[j];
|
|
|
node->next = NULL;
|
|
|
int index = keys[j] / 10;
|
|
|
KeyNode *p = bucket_table[index];
|
|
|
if (p->key == 0) {
|
|
|
bucket_table[index]->next = node;
|
|
|
(bucket_table[index]->key)++;
|
|
|
}
|
|
|
else {
|
|
|
while (p->next != NULL && p->next->key <= node->key)
|
|
|
p = p->next;
|
|
|
node->next = p->next;
|
|
|
p->next = node;
|
|
|
(bucket_table[index]->key)++;
|
|
|
}
|
|
|
}
|
|
|
//print result
|
|
|
KeyNode * k = NULL;
|
|
|
for (i = 0; i < bucket_size; i++)
|
|
|
for (k = bucket_table[i]->next; k != NULL; k = k->next)
|
|
|
printf("%d ", k->key);
|
|
|
printf("\n");
|
|
|
}
|
|
|
|
|
|
|
|
|
int main()
|
|
|
{
|
|
|
int raw[] = { 49,38,65,97,76,13,27,49 };
|
|
|
int size = sizeof(raw) / sizeof(int);
|
|
|
bucket_sort(raw, size, 10);
|
|
|
}
|
|
|
|
|
|
/*三、桶排序算法特点
|
|
|
1.时间复杂度
|
|
|
桶排序算法遍历了2次原始数组,运算量为2N,最后,遍历桶输出排序结果的运算量为N,初始化桶的运算量为M。
|
|
|
|
|
|
对桶进行排序,不同的排序算法算法复杂度不同,冒泡排序算法复杂度为O(N^2),堆排序、归并排序算法复杂度为O(NlogN),我们以排序算法复杂度为O(NlogN)进行计算,运算量为N/M*log(N/M)*M
|
|
|
|
|
|
最终的运算量为3N+M+N/M*log(N/M)*M,即3N+M+N(logN-logM),去掉系数,时间复杂度为O(N+M+N(logN-logM))
|
|
|
|
|
|
2.空间复杂度
|
|
|
桶排序算法排序过程中新建了一个桶和一个输出数组,所以算法的空间复杂度是O(N+M)
|
|
|
|
|
|
3.稳定性
|
|
|
桶排序算法在对每个桶进行排序时,选择稳定的排序算法,则排序后,相同元素的位置不会发生改变,所以桶排序算法是一种稳定的排序算法*/
|