排序算法之计数排序

计数排序
统计记录表中每个记录的比该记录小的记录个数,得出该记录应排的位置


#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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值