排序算法之计数排序
程序员文章站
2022-03-24 13:52:46
...
计数排序
统计记录表中每个记录的比该记录小的记录个数,得出该记录应排的位置
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType otherinfo;
}RedType;
typedef struct
{
RedType r[MAXSIZE+1];
int length;
}SqList;
int LT(KeyType a,KeyType b);
void CountingSort(SqList*L1,SqList *L2);
int main()
{
SqList *L,*L1,*L2;
L=(SqList *)malloc(sizeof(SqList));
L1=(SqList *)malloc(sizeof(SqList));
L2=(SqList *)malloc(sizeof(SqList));
int i;
printf("需排序的项数为:");
scanf("%d",&L->length);
for(i=1;i<=L->length;i++)
{
printf("please input the number:");
scanf("%d",&L->r[i].key);
}
L1->length=L->length;
CountingSort(L,L1);
printf("计数排序的结果:");
for(i=1;i<=L1->length;i++)
{
printf("%d ",L1->r[i].key);
}
printf("\n");
return 0;
}
int LT(KeyType a,KeyType b)
{
return a<b;
}
void CountingSort(SqList *L1,SqList *L2)
{
int i,j,*count;
count=(int *)malloc(sizeof(int)*(L1->length+1));
for(i=1;i<=L1->length;i++)
count[i]=0;
for(i=1;i<=L1->length;i++)
{
for(j=i+1;j<=L1->length;j++)
if(LT(L1->r[j].key,L1->r[i].key))
count[i]++;
else
count[j]++;
L2->r[count[i]+1]=L1->r[i];
}
free(count);
}
上一篇: 排序算法总结(7)--归并排序
下一篇: python 堆排序的两种实现