BucketSort

#include <stdio.h>
#include <stdlib.h>

typedef struct elem {
	int val;
	struct elem *next;
} Elem;

#define BUFSIZE 10

// 100以内
void BucketSort(int *A, int n)
{
	Elem **B = (Elem **)malloc(n * sizeof(Elem *));
	if (!B) {
		printf("B malloc error\n");
		return ;
	}
	for (int i = 0; i < n; i++) 
 		B[i] = NULL;
	
	for (int i = 0; i < n; i++) {
		Elem *p = (Elem *)malloc(sizeof(Elem));
		if (!p) {
			printf("p malloc error\n");
			return ;
		}
		p->val = A[i];
		p->next = NULL;

		if (B[A[i]/10] == NULL) {
			B[A[i]/10] = p;
		} else {
			Elem *q = B[A[i]/10];
			if (p->val < q->val) { // 在头部插入
				p->next = B[A[i]/10];
				B[A[i]/10] = p; // 这里的B[A[i]/10]千万不能用q,坑 
			} else {
				Elem *prev = q; // 保存前一个节点
				while (p->val >= q->val) {
					prev = q;
					q = q->next;
				}
				p->next = prev->next;
				prev->next = p;
			}
		}
	}

	for (int i = 0, j = 0; i < n; i++) {
		Elem *pe = B[i];
		while (pe) {
			Elem *tmp = pe;
			A[j++] = pe->val;
			pe = pe->next;
			free(tmp);
		}
	}

	free(B);
}

int main()
{
	int A[BUFSIZE] = {8, 17, 39, 26, 72, 94, 21, 12, 23, 68};
	int n = sizeof(A) / sizeof(A[0]);

	for (int i = 0; i < n; i++)
		printf("%d\t", A[i]);
	printf("\n");
	BucketSort(A, n);
	for (int i = 0; i < n; i++)
		printf("%d\t", A[i]);
	printf("\n");

	system("pause");
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值