c - 在 C 中修剪 int 数组以进行桶排序

标签 c arrays sorting

我正在用C语言编写一个桶排序程序。当我将小桶合并成一个大桶后,我需要删除我填充小桶的-1。

我对 C 还很陌生,所以可能有一个我忽略的非常简单的解决方案。

这是我的解决方案,它似乎返回一个带有 1 个尾随垃圾值和尾随 0 的数组,填充该数组,直到它达到未修剪存储桶的大小(其中所需的结果是没有 -1 和垃圾值的存储桶,和尾随 0)。

    // A function to trim a bucket of a given size to a bucket containing no -1s
    int* trimBucket(int* bucket, int size)
    {
        int n = 0, i = 0;
        int* newBucket;

        // This loop is to count the number of elements between 0 and 9999
        for(n = 0; n < size; n++) 
        {
            if(bucket[n] != -1 && bucket[n] < 10000)
                i++;
        }

        // Create a new bucket equal to the number of elements counted
        // Filled with -2 to differentiate from -1s contained in the bucket array
        newBucket = allocateAndInitiateOneD(i, -2); 
        i = 0;

        for(n = 0; n < size; n++)
        {
            // I only want values between 0-9999 to be put into the new array
            if(bucket[n] != -1 && bucket[n] < 10000) 
            {
                newBucket[i] = bucket[n];
                i++;
            }       
        }

        free(bucket); // Am I doing this right?
        return newBucket;
    }

allocateAndInitiateOneD 函数:

    // A function to allocate memory for a one dimensional array and fill it with the given value
    int* allocateAndInitiateOneD(int x, int initialNum)
    {
        int runs = 0;
        int* oneArray;

        oneArray = malloc(sizeof(int) * x);

        for(runs = 0; runs < x; runs++)
            oneArray[runs] = initialNum;

        return oneArray;
    }

有人可以帮助我了解我做错了什么以及如何获得所需的结果吗?

感谢您的帮助!

编辑:我正在Unix系统上编译并运行。可能不相关,但这是一个使用 MPI 库的多处理程序(这似乎不是问题所在)。

最佳答案

看起来一切正常,但是您还需要从此函数返回新的大小,而不知道数组的长度,您可以直接读取新选择的大小的末尾,它看起来像垃圾(1 个尾随垃圾值和全零...)。

C 中的数组始终有两部分。起始指针和大小。有时大小是隐式的,但它需要以某种方式存在,否则您将永远继续阅读。

如果您需要从函数返回多个内容,可以:

  • 通过指针参数返回(一个或两个)
  • 通过结构体返回它们

关于c - 在 C 中修剪 int 数组以进行桶排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17980493/

相关文章:

python - Numpy 数组排除一些元素

ruby - 按值对哈希进行排序时如何保留键的字母顺序

c - 无法使用 fgets 函数读取字符串

c++ - 如何在循环中使用多维字符或字符串数​​组

c++ - 如何以正确的方式将结构数组参数传递给函数?

Javascript localecompare - 首先排序的大写字母

javascript - 如何使用 Angular2 管道按离今天最近的日期排序

c - 用更有意义的文本替换 GCC 输出中的 a-hats

c - 在自定义结构中管理可动态分配的数组

c - 与指针大小相同的浮点类型