排序之珠排序

先看一段动态图:

 

 

未排序前:  2  6  5  4  8  3

排序后:      2  3  4  5  6  8

 

步骤:

1. 每个数都分为几个1,然后在一个两维数组(待排序数组长度,数组中数的最大值)中制作珠子

2.珠子掉落

3.从上到下依次遍历,确定升序序列

 

代码如下:

#include <stdio.h>
#include <stdlib.h>
 
/**
 * @addtogroup sorting Sorting algorithms
 * @{
 */
/** Create easy access of elements from a 2D matrix stored in memory as a 1D
 * array
 */
#define BEAD(i, j) beads[i * max + j]
 
/**
 * Displays the array, passed to this method
 * @param [in] arr array to display
 * @param [in] n number of elements in the array
 */
void display(const int *arr, int n)
{
    int i = 0;
 
    for (; i < n; i++)
    {
        printf("%d ", arr[i]);
    }
 
    printf("\n");
}
 
/** This is where the sorting of the array takes place
 * @param [in,out] a array to be sorted
 * @param [in] len Array Size
 */
void bead_sort(int *a, size_t len)
{
    int i, j, max, sum;
    unsigned char *beads;
 
    for (i = 1, max = a[0]; i < len; i++)
        if (a[i] > max)
            max = a[i];
 
    beads = calloc(1, max * len);
 
    /* mark the beads */
    for (i = 0; i < len; i++)
        for (j = 0; j < a[i]; j++)
            BEAD(i, j) = 1;
 
    for (j = 0; j < max; j++)
    {
        /* count how many beads are on each post */
        for (sum = i = 0; i < len; i++)
        {
            sum += BEAD(i, j);
            BEAD(i, j) = 0;
        }
        /* mark bottom sum beads */
        for (i = len - sum; i < len; i++)
            BEAD(i, j) = 1;
    }
 
    for (i = 0; i < len; i++)
    {
        for (j = 0; j < max && BEAD(i, j); j++)
            ;
        a[i] = j;
    }
    free(beads);
}
/** @} */
 
/** Main function */
int main(int argc, const char *argv[])
{
    int n = 0;
    int i = 0;
    int *arr = NULL;
 
    printf("Enter size of array:\n");
    scanf("%d", &n);  // E.g. 8 1 2 3
 
    printf("Enter the elements of the array\n");
     
    arr = (int *)malloc(n * sizeof(int));
 
     
    for (; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }
 
    printf("Original array: ");
    display(arr, n);
 
    bead_sort(arr, n);
 
    printf("Sorted array: ");
    display(arr, n);
 
    free(arr);
 
    system("pause");
 
    return 0;
}

  运行结果:

 

posted on   wu.g.q  阅读(78)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示