基数排序:
我的理解:其实就是对数组的每个元素,从个位开始进桶排序,再十位进桶排序.......。给图解释吧!
看这图理解会更好理解一点。
看看代码吧!
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<assert.h>
#include<vld.h>
#include"LINK_QUEUE.h"
void base_sort(int *arr,int len,int radix,int max_base)
{
LINK_QUEUE **bucket = (LINK_QUEUE **)malloc(sizeof(LINK_QUEUE *) * radix);
assert(bucket != NULL);
int tmp ;
for(int i = 0;i < radix;i ++)
{
bucket[i] = init_queue();
}
for(int i = 0;i < max_base;i ++)
{
for(int j = 0;j < len;j ++)//让数组进桶
{
int m = arr[j]/(int)pow((double)radix ,i) % radix;
push(bucket[m],arr[j]);
}
int n = 0;
for(int k = 0;k < radix ;k++)//从桶里出来,放进数组
{
while(!is_empty(bucket[k]))
{
pop(bucket[k],&tmp);
arr[n] = tmp;
n ++;
}
}
}
for(int i = 0;i < radix;i ++)
{
destory_queue(*(bucket + i));
}
free(bucket);
}
int get_max_base(int *arr,int len)
{
int max = *arr;
int i = 0;
while(len)
{
if(max < *(arr + 1))
{
max = *(arr + 1);
}
arr = arr + 1;
len --;
}
while(max)
{
i ++;
max = max/10;
}
return i;
}
int main()
{
int arr[] = {278,109,63,930,589,184,505,269,8,84};
int radix = 10;
int len = sizeof(arr)/sizeof(arr[0]);
int m = get_max_base(arr,sizeof(arr)/sizeof(arr[0]));
base_sort(arr,len,radix,m);
for(int i = 0;i < len ; i ++)
{
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}
push和pop是在#include"LINK_QUEUE.h"里面引进来的队的应用,
bool push(LINK_QUEUE *p, elem_type e)
{
NODE *tmp = alloc(e);
if(p == NULL)
{
return false;
}
if(!is_empty(p))
{
p->tail->next = tmp;
}
else
{
p->head = tmp;
}
p->tail = tmp;
p->length ++;
return true;
}
bool pop(LINK_QUEUE *p, elem_type *e)
{
NODE *s = p->head;
if(p == NULL ||is_empty(p))
{
return false;
}
if(p->length == 1)
{
p->tail = NULL;
}
*e = p->head->data;
p->head = s->next;
p->length --;
free(s);
return true;
}
ok!完成
运算结果: