桶排序



#include<iostream>
#include<iomanip>
#include<cmath>
#define BASE 10
using namespace std;

//桶中元素链表
typedef struct entry
{
	int element;
	struct entry *next;
}ENTRY;

//维护每个桶中元素数目,并且指向第一个元素
typedef struct buc
{
	int size;
	ENTRY *head;
}BUCKET;


//桶内数据使用插入排序
void insertSort(BUCKET &bucket, const int &element)
{
	ENTRY *tmp = bucket.head;
	ENTRY *en = (ENTRY*)malloc(sizeof(ENTRY));
	en->element = element;
	en->next = NULL;
	if ((tmp == NULL) || (tmp->element > en->element))
	{
		en->next = tmp;
		bucket.head = en;
		bucket.size++;
	}
	else
	{
		while (tmp != NULL)
		{
			if ((tmp->next == NULL&&tmp->element <= en->element) || (tmp->element <= en->element&&tmp->next->element > en->element))
			{
				en->next = tmp->next;
				tmp->next = en;
				bucket.size++;
				break;
			}
			tmp = tmp->next;
		}
	}

}

int hasha(int data)
{
	return data / 11;
}


//使用插入排序将数据分别插入对应的桶中
void createBucket(BUCKET *buckets, int *data, int n)
{
	for (int i = 0; i < n; i++)
	{
		int num = hasha(data[i]);
		insertSort(buckets[num], data[i]);
	}
}


//将以排序数据反向输入到数组中
void reverseEvaluation(BUCKET *buckets, int *data, int n)
{
	int idx = 0;
	for (int i = 0; i < n; i++)
	{
		if (buckets[i].size != 0)
		{
			ENTRY *en = buckets[i].head;
			while (en != NULL)
			{
				data[idx++] = en->element;
				en = en->next;
			}
		}
	}
}



void bucketSort(int *data, int n)
{
	//创建并初始化桶的头结点
	BUCKET *buckets = (BUCKET*)malloc(sizeof(BUCKET)*n);
	for (int i = 0; i < n; i++)
	{
		buckets[i].size = 0;
		buckets[i].head = NULL;
	}
	
	//向桶中放数据
	createBucket(buckets, data,n );
	
	//将桶中数据反向输入到数组
	reverseEvaluation(buckets, data, n);
	
	//释放内存
	free(buckets);
}


void main()
{
	int arr[] = { 10, 20, 15, 17, 28, 32, 21, 41, 33, 11 };
	int length = sizeof(arr) / sizeof(int);
	for (int i = 0; i < length; i++)
		cout << arr[i] << " ";
	cout << endl;

	bucketSort(arr, length);
	for (int i = 0; i < length; i++)
		cout << arr[i] << " ";
	cout << endl;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值