【排序之一】桶排序

桶排序代碼引用自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;



}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章