基於非比較的排序 通過以數據不同位分別爲基準裝桶的操作達到排序的目的 有LSD和MSD 即低位優先和高位優先兩種裝桶方法
---C語言實現
---以兩位數爲例
---LSD
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define STANDARDDATASEP 10
typedef struct hashnode
{
int value;
struct hashnode *pNext;
}HashNode;
//遍歷數組
void LoopForArr(int arr[],int length)
{
int count;
if(arr == NULL || length <=0)return ;
for(count = 0;count<length;count++)
{
printf("%d ",arr[count]);
}
printf("\n");
}
//利用哈希分桶
void CreateHashForRadixSort(HashNode** Head,int SepDigit,int arr[],int length)
{
int count;
int sepdata = 1;
HashNode *Temp = NULL;
HashNode *Temp_in = NULL;
while(--SepDigit)
{
sepdata*=STANDARDDATASEP;
}
//尾添加 穩定
for(count = 0;count<length;count++)
{
Temp = (HashNode *)malloc(sizeof(HashNode));
Temp->value = arr[count];
Temp->pNext = NULL;
if( !Head[arr[count]/sepdata%10] )
{
Head[arr[count]/sepdata%10] = Temp;
}
else
{
Temp_in = Head[arr[count]/sepdata%10];
while(Temp_in->pNext)
{
Temp_in = Temp_in->pNext;
}
Temp_in->pNext = Temp;
}
}
}
//基數排序 LSD
void RadixSort(int arr[],int length)
{
int count;
int count_in;
int min;
int max;
int max_digit;
int count_hash;
HashNode**Head = NULL;
HashNode*Temp = NULL;
if(arr == NULL || length <=0)return ;
//找最大值 最小值
min = max = arr[0];
for(count = 1;count<length;count++)
{
min = arr[count]<min?arr[count]:min;
max = arr[count]>max?arr[count]:max;
}
//數據分析
max_digit = 0;
while(max)
{
max_digit++;
max/=STANDARDDATASEP;
}
//申請桶
Head = (HashNode **)malloc(sizeof(HashNode* )*STANDARDDATASEP);
memset(Head,0,sizeof(HashNode* )*STANDARDDATASEP);
for(count = 1;count<=max_digit;count++)
{
//哈希分桶
CreateHashForRadixSort(Head,count,arr,length);
//倒回原數組
count_in = 0;
count_hash = 0;
while(count_in<length)
{
while(!Head[count_hash])
count_hash++;
Temp = Head[count_hash];
while(Temp)
{
arr[count_in++] = Temp->value;
Temp = Temp->pNext;
}
count_hash++;
}
//釋放桶內空間
--count_hash;
while(count_hash>=0)
{
Temp = Head[count_hash];
while(Temp)
{
Head[count_hash] = Temp;
Temp = Temp->pNext;
free(Head[count_hash]);
Head[count_hash] = NULL;
}
count_hash--;
}
}
free(Head);
Head = NULL;
}
int main()
{
int count = 0;
int arr[] = {36,49,30,12,28,16,17,31,26,55,66,91};
RadixSort(arr,sizeof(arr)/sizeof(arr[0]));
for(;count < sizeof(arr)/sizeof(arr[0]);count++)
{
printf("%d ",arr[count]);
}
system("pause");
return 0;
}
排序