【排序之一】桶排序

桶排序代码引用自http://blog.csdn.net/lg1259156776/

被问到求一些无序数据相邻之间的最小间隔,已知这些数<n,可以用桶排序,时间复杂度为o(n)。

先写代码,其他的关于桶排序后续补充

#include<iostream>
#include<iomanip>
using namespace std;

#define NARRAY 8//array size
#define NBUCKET 5//bucket size
#define INTERVAL 10//bucket range

struct Node
{
	int data;
	struct Node * next;
};

void BucketSort(int arr[]);
struct Node * InsertionSort(struct Node * list);
void printm(int arr[]);
void printBuckets(struct Node * list);
int getBucketIndex(int value);

void BucketSort(int arr[])
{
	int i, j;
	struct Node **buckets;

	//allocate  memory for each bucket
	buckets = (struct Node **)malloc(sizeof(struct Node*)*NBUCKET);

	//initialize
	for (i = 0; i < NBUCKET; i++)
	{
		buckets[i] = NULL;
	}

	for (i = 0; i < NARRAY; i++)
	{
		struct Node * current;
		int pos = getBucketIndex(arr[i]);
		current = (struct Node*)malloc(sizeof(struct Node));
		current->data = arr[i];
		current->next = NULL;
		//insert into queue head
		current->next = buckets[pos];
		buckets[pos] = current;
	}

	//sort every bucket
	for (i = 0; i < NBUCKET; i++)
	{
		buckets[i] = InsertionSort(buckets[i]);
	}

	//put the data into original array
	j = 0;
	for (i = 0; i < NBUCKET; i++)
	{
		struct Node * n = buckets[i];
		while (n)
		{
			arr[j] = n->data;
			j++;
			n = n->next;
		}
	}

	//free memory
	for (i = 0; i < NBUCKET; i++)
	{
		struct Node * n;
		n = buckets[i];
		while (n)
		{
			struct Node * tmp;
			tmp = n;
			n = n->next;
			free(tmp);
		}
	}

	free(buckets);
}

struct Node * InsertionSort(struct Node * list)
{
	struct Node * k, *nodeList;
	if (list == 0 || list->next == 0)
	{
		return list;
	}

	nodeList = list;
	k = list->next;
	nodeList->next = 0;
	while (k != 0)
	{
		struct Node * ptr;
		//check if insert before first
 		if (nodeList->data > k->data)
		{
			struct Node * tmp;
			tmp = k;
			k = k->next;
			tmp->next = nodeList;
			nodeList = tmp;
			continue;
		}

		for (ptr = nodeList; ptr->next != 0; ptr = ptr->next)
		{
			if (ptr->next->data > k->data) break;
		}

		if (ptr->next != 0)
		{
			struct Node * tmp;
			tmp = k;
			k = k->next;
			tmp->next = ptr->next;
			ptr->next = tmp;
			continue;
		}
		else
		{
			ptr->next = k;
			k = k->next;
			ptr->next->next = 0;
			continue;
		}
	}
	return nodeList;
}

int getBucketIndex(int value)
{
	return value / INTERVAL;
}

int main()
{

	int arr[] = {29,25,3,49,9,37,21,43};
	BucketSort(arr);
	for (int i = 0; i < NARRAY; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
	return 0;



}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值