#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DATALEN 3
char three_letter_words[][DATALEN + 1] =
{"cow","low","add","tip","bat","dog","cat"};
int length = sizeof(three_letter_words) / sizeof(three_letter_words[0]);
#define DEBUG printf
typedef struct stRadixBuf
{
unsigned long handle;
char* buf;
}RadixBuf;
RadixBuf* g_src = NULL;
RadixBuf* g_dst = NULL;
void create_radix_buf(RadixBuf** ppRadixBuf)
{
RadixBuf* pRadixBuf;
if (*ppRadixBuf == NULL)
{
pRadixBuf = (RadixBuf*)malloc(sizeof(RadixBuf) * length);
if (pRadixBuf)
{
for (int i = 0; i < length; i++)
{
pRadixBuf[i].buf = (char*)malloc((DATALEN + 1) * sizeof(char));
memset(pRadixBuf[i].buf, 0, sizeof(char) * (DATALEN + 1));
pRadixBuf[i].handle = (unsigned long)(void*)(pRadixBuf[i].buf);
}
*ppRadixBuf = pRadixBuf;
}
}
}
void print_radix_buf(RadixBuf* pRadixBuf,const char* name)
{
DEBUG("print radix buf: %s \n",name);
for (int i = 0; i < length; i++)
{
DEBUG("handle: %lx str: %s \n",pRadixBuf[i].handle,pRadixBuf[i].buf);
}
DEBUG("\n");
}
void ini_radix_buf()
{
create_radix_buf(&g_src);
create_radix_buf(&g_dst);
}
void free_radix_buf(RadixBuf* pRadixBuf)
{
if (pRadixBuf)
{
for (int i = 0; i < length; i++)
{
free(pRadixBuf[i].buf);
}
free(pRadixBuf);
}
}
/*把原始数据存到基数结构体中*/
void assign_radix_buf(RadixBuf* pRadixBuf, char(*pSrc)[DATALEN + 1])
{
for (int i = 0; i < length; i++)
{
strcpy_s(pRadixBuf[i].buf, DATALEN + 1,(char *)pSrc + (DATALEN + 1) * i);
}
}
#define LITTLE_LETTER_NUM 26
int g_cnt[LITTLE_LETTER_NUM];
void copy_radix_buf(RadixBuf* pDst, RadixBuf* pSrc)
{
for (int i = 0; i < length; i++)
{
pDst[i].handle = pSrc[i].handle;
strcpy_s(pDst[i].buf, DATALEN + 1, pSrc[i].buf);
}
}
void radix_sort()
{
int loopLetters;
for (loopLetters = DATALEN - 1; loopLetters >= 0; loopLetters--)
{
int i;
memset(g_cnt, 0, sizeof(int) * LITTLE_LETTER_NUM);
/*统计字符出现的个数*/
for (i = 0; i < length; i++)
{
g_cnt[g_src[i].buf[loopLetters] - 'a'] += 1;
}
/*统计累加值*/
for (i = 1; i < LITTLE_LETTER_NUM; i++)
{
g_cnt[i] = g_cnt[i] + g_cnt[i - 1];
}
for (i = length - 1; i >= 0; i--)
{
/*计数排序,更新计数*/
int dstInd = g_cnt[g_src[i].buf[loopLetters] - 'a'];
g_cnt[g_src[i].buf[loopLetters] - 'a'] = dstInd - 1;
g_dst[dstInd - 1].handle = g_src[i].handle;
strcpy_s(g_dst[dstInd - 1].buf,DATALEN + 1, g_src[i].buf);
}
copy_radix_buf(g_src,g_dst);
DEBUG("after loopLetters %d \n",loopLetters);
print_radix_buf(g_dst, "src");
}
}
void recycle_radix_buf()
{
free_radix_buf(g_src);
free_radix_buf(g_dst);
}
int main()
{
ini_radix_buf();
assign_radix_buf(g_src, three_letter_words);
DEBUG("before radix sort \n");
print_radix_buf(g_src,"src");
radix_sort();
DEBUG("after radix sort \n");
print_radix_buf(g_src, "src");
recycle_radix_buf();
return 0;
}
radix_sort
最新推荐文章于 2023-12-27 08:48:29 发布