您的位置:首页 > 其它

基数排序(RADIX SORT

2017-04-20 16:45 337 查看
#include <stdio.h>
#include <stdlib.h>

#define N 3

typedef struct bucket_tag bucket;
typedef struct bucket_tag
{
bucket *next;
int value;
}*pbucket;

int fpow(int n, int k)
{
int i;
int ppow = 1;
for (i = 0; i < k; i++)
ppow *= n;
return ppow;
}

pbucket *CreateBucket(void) // create 10 bucekts
{
pbucket *root = (pbucket *)malloc(10 * sizeof(pbucket));
int i;

for (i = 0; i < 10; i++)
root[i] = (pbucket)malloc(sizeof(bucket));
for (i = 0; i < 10; i++)
{
root[i]->next = NULL;
root[i]->value = i;
}
root[9]->next = NULL;
root[9]->value = 9;

return root;
}

void AddNode(pbucket root, int num_value)
{
pbucket pnode = root;

while (pnode->next != NULL)
{
pnode = pnode->next;
}
pnode->next = (pbucket)malloc(sizeof(bucket));
pnode->next->value = num_value;
pnode->next->next = NULL;
}
void DeleteNode(pbucket previous, pbucket current)
{
previous->next = current->next;
free(current);
}

void BucketSort(int a[], int num) // the main drive programme
{
pbucket *radix = CreateBucket();
// the buckets

pbucket pnode;
int i, j, k;
int roundnum;

for (i = 1; i <= N; i++)
{
for (j = 0; j < num; j++)
{
roundnum = ((a[j] / fpow(10, i - 1)) % 10);
AddNode(radix[roundnum], a[j]);
}

k = 0;
for (j = 0; j < 10; j++)
{
while (radix[j]->next != NULL)
{
pnode = radix[j]->next;
a[k] = pnode->value;
DeleteNode(radix[j], pnode);
k = k + 1;
}
}
}

}

基数排序,桶式排序。在一定数据范围内,算法复杂度仅仅为 O(n)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  基数排序