桶排序_改进结构体

来源:互联网 发布:广电网络招聘 编辑:程序博客网 时间:2024/06/08 16:03

用typedef *BUCKET 替代原本的struct和指针,有点把结构体指针当类用的感觉啊……


#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");}typedef struct bucket {int key;struct bucket *next;}*Bucket;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;Bucket pBucket,p;pBucket = (Bucket) malloc(sizeof(Bucket) * buck_num);memset(pBucket, 0, sizeof(Bucket) * buck_num);p = (struct bucket*)malloc(sizeof(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;Bucket newBucket;newBucket = (Bucket)malloc(sizeof(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
原创粉丝点击