桶排序

来源:互联网 发布:mac装ros 编辑:程序博客网 时间:2024/05/16 11:21


思路:计算数组的值域,以10为差值区间映射入桶中,每个桶用链表的结构存储,对新数据按插入排序插入,最后遍历桶,得到最终序列


#include <stdio.h>#include <stdlib.h>#define LENGTH 10000001int a[LENGTH];void print(int* a, int x, int y) {int i;for (i = x; i < y + 1; i++)printf("%d ", a[i]);printf("\n");}struct bucket {int key;struct bucket *next;};void bucket_sort(int* a, int n) {int i, k;int min, max, buck_num;min = max = a[0];for (i = 0; i < n; i++) {min = a[i] < min ? a[i] : min;max = a[i] > max ? a[i] : max;}buck_num = (max - min + 1) / 10 + 1;struct bucket *pBucket,*p;pBucket = (struct bucket*) malloc(sizeof(struct bucket) * buck_num);memset(pBucket, 0, sizeof(struct bucket) * buck_num);p = (struct bucket*)malloc(sizeof(struct bucket));for (i = 0; i < buck_num; i++){p = pBucket + i;p->next = NULL;}for (i = 0; i < n; i++) {k = (a[i] - min + 1) / 10;p = pBucket + k;struct bucket *newBucket;newBucket = (struct bucket*)malloc(sizeof(struct bucket));while(p->next != NULL){if(p->next->key > a[i])break;p = p->next;}newBucket->key = a[i];newBucket->next = p->next;p->next = newBucket;}int pos = 0;for (i = 0; i < buck_num; i++){p = pBucket + i;while(p->next != NULL){p = p->next;a[pos++] = p->key;}}}int main() {//freopen("sort.in", "r", stdin);int n, i;scanf("%d", &n);for (i = 0; i < n; i++)scanf("%d", &a[i]);bucket_sort(a, n);print(a,0,n-1);return 0;}


0 0
原创粉丝点击