排序算法之桶排序

  • 原理
    将待排序数,按照个位,一次进桶,再按桶的顺序依此出桶,再按十尾依此进桶出桶,再按百位进同出桶。。。

  • 步骤

(1)设置一个定量的数组当作空桶子; 
(2)寻访序列,并且按照要求把记录一个一个放到对应的桶子去; 
(3)对每个不是空的桶子进行排序。 
(4)从不是空的桶子里把项目再放回原来的序列中。
  • 性能
    稳定性:稳定
    时间复杂度:O(d*n)(d表示趟数 )
    空间复杂度:O(n)

  • 实现

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node
{
    int data;
    struct Node *next;
}Node,*List;


void Init(List plist)
{
    assert(plist != NULL);
    plist->next = NULL;
}

static Node *BuyNode(int val)
{
    Node *p = (Node*)malloc(sizeof(Node));
    assert(p !=NULL);
    p->data = val;
    p->next = NULL;
    return p;
}

void Insert(List plist,int val)
{
    Node *p = plist;
    for(;p->next != NULL;p=p->next)
    {
        ;
    }
    Node *q = BuyNode(val);
    p->next = q;
}

bool DeleteFirst(List plist,int *rtval)
{
    Node *p = plist->next;
    if (p == NULL)
    {
        /* code */
        return false;
    }
    *rtval = p->data;
    plist->next = p->next;
    free(p);
    return true;
}

int GetNum(int num,int figure)
{
    for (int i = 0; i < figure; ++i)
    {
        /* code */
        num /= 10;
    }
    return num %10;
}

int GetMaxFigure(int *arr,int len)
{
    int max = arr[0];
    int count = 0;
    for (int i = 0; i < len; ++i)
    {
        /* code */
        if (arr[i] > max)
        {
            /* code */
            max = arr[i];
        }
    }
    while(max != 0)
    {
        count++;
        max /= 10;
    }
    return count;
}

void Radix(int *arr,int len,int figure)
{
    int tmp;
    Node head[10];
    int i = 0;
    for (i = 0; i < 10; ++i)
    {
        /* code */
        Init(&head[i]);
    }

    for (i = 0; i < len; ++i)
    {
        /* code */
        tmp = GetNum(arr[i],figure);
        Insert(&head[tmp],arr[i]);
    }
    i = 0;
    for (int j = 0; j < 10; )
    {
        /* code */
        if (DeleteFirst(&head[j],&arr[i]))
        {
            /* code */
            i++;
        }
        else
        {
            j++;
        }
    }
}


void RadixSort(int *arr,int len)
{
    int figure = GetMaxFigure(arr,len);
    for (int i = 0; i < figure; ++i)
    {
        /* code */
        Radix(arr,len,i);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值