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