You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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.稳定性
桶排序算法在对每个桶进行排序时,选择稳定的排序算法,则排序后,相同元素的位置不会发生改变,所以桶排序算法是一种稳定的排序算法*/