C 数组算法中的最大数

标签 c algorithm

所以,我只是在处理 C 代码,尤其是接受 3 个参数的函数:一个数组、数组的大小以及您想要返回的最大元素数。

这是我的代码:

int* findMaxElements(int base_array[],int size_of_base_array, int number_of_elements_to_find);

int main( void )
{

    printf("Find Max Values in an Array\n\n");

    // Set up array

    int kinch[6] = {1,2,3,4,5,6};

    // Pass to function and get a pointer to new array filled with only the max elements

    int *given = findMaxElements(kinch,6,3);

    for(int i = 0; i < 3; i++)
    {
        printf("\nMax Value = %d\n", *(given + i));
    }
    return 0;

}

int* findMaxElements(int base_array[],int size_of_base_array, int number_of_elements_to_find)
{

    // Set up all initial variables

    int i,k,c,position;
    int maximum = 0;



    int returnArray[100];

    /*Actual Algorythm */

    for(i = 0; i < number_of_elements_to_find; i++)
    {

        // Get the max value in the base array

        for(k = 0; k < size_of_base_array; k++)
        {
            if(base_array[k] > maximum)
            {
                maximum = base_array[k];
            }
        }

        // Find the position of the max value

        for(position = 0; position < size_of_base_array; position++)
        {

            if(base_array[position] == maximum)
            {
                break;
            }

        }

        // Delete the maximum value from the array and shift everything

        for(c = position - 1; c < size_of_base_array - 1; c++)
        {
            base_array[c] = base_array[c+1];
        }

        // Reduce the size of the array

        size_of_base_array -= 1;

        // Push max value into return array

        returnArray[i] = maximum;

        // Reset max value

        maximum = 0;
    }

    return returnArray;

}

我感觉函数中某处出了问题。

// Set up array

    int kinch[6] = {1,2,3,4,5,6};

    // Pass to function and get a pointer to new array filled with only the max elements

    int *given = findMaxElements(kinch,6,3);

    for(int i = 0; i < 3; i++)
    {
        printf("\nMax Value = %d\n", *(given + i));
    }

这应该输出数字 6、5 和 4,因为它们是数组中最大的三个,但是我得到的输出始终是 6、6 和 6。它有什么问题吗?

最佳答案

这可能不是你唯一的问题,但在行中

for(c = position - 1; c < size_of_base_array - 1; c++)
    {
        base_array[c] = base_array[c+1];
    }

您将位于 [c+1] 的元素(这是最大值)复制到 [c] - 这样您就可以不断找到最大值...

您应该以 c = position 开始循环,而不是 c = position - 1

并在用于存储返回值的数组前面添加关键字 static,使它们保持有效(这是解决 Jonathan Leffler 发现的问题的一种方法)。

关于C 数组算法中的最大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16004600/

相关文章:

c - 使用 PBC 将一个元素散列到另一个元素中

c - 当写入发生在多个目录中时,磁盘写入性能会下降

algorithm - 具有彩色边缘的图形中更改次数最少的路径

algorithm - 大 O 符号的总和

algorithm - 卡方检验算法

c - 从随机 id 中检索元素的最佳算法

c - 如何编写makefile在不同目录中生成目标文件和可执行文件?

c - 链接后出现意外输出

c++ - 避免此功能的递归

C 数组中第一个索引处的未知访问冲突