我有以下函数在矩阵中找到最大值和最小值,如何添加MIN和MAX的结构,以便只能够找到最小值和最大值的函数?

int maximum(int array[], int index, int len)
{
    int max;

    if(index >= len-2)
    {
        if(array[index] > array[index + 1])
            return array[index];
        else
            return array[index + 1];
    }




    max = maximum(array, index + 1, len);

    if(array[index] > max)
        return array[index];
    else
        return max;
}

int minimum(int array[], int index, int len)
{
    int min;

    if(index >= len-2)
    {
        if(array[index] < array[index + 1])
            return array[index];
        else
            return array[index + 1];
    }

    min = minimum(array, index + 1, len);

    if(array[index] < min)
        return array[index];
    else
        return min;
}

最佳答案

#include <assert.h>
#include <stddef.h>
#include <stdio.h>

typedef struct minmax_tag {
    int min;
    int max;
} minmax_t;

minmax_t get_minmax(int const *data, size_t length)
{
    assert(length);

    minmax_t minmax = { data[0], data[0] };

    for (size_t i = 1; i < length; ++i) {
        if (data[i] < minmax.min)
            minmax.min = data[i];
        if (data[i] > minmax.max)
            minmax.max = data[i];
    }

    return minmax;
}

int main(void)
{
    int foo[] = { 12, 484, 487, 1, 500 };
    minmax_t result = get_minmax(foo, sizeof(foo) / sizeof(*foo));
    printf("Min: %d\tMax: %d\n\n", result.min, result.max);
}

Sowwy,递归:
#include <assert.h>
#include <stddef.h>
#include <stdio.h>

typedef struct minmax_tag {
    int min;
    int max;
} minmax_t;

minmax_t get_minmax_impl(int const *data, size_t pos, size_t length, minmax_t previous)
{
    if (pos == length)
        return previous;

    if (data[pos] < previous.min)
        previous.min = data[pos];
    if (data[pos] > previous.max)
        previous.max = data[pos];

    return get_minmax_impl(data, pos + 1, length, previous);
}

minmax_t get_minmax(int const *data, size_t length)
{
    assert(length);

    minmax_t previous = { data[0], data[0] };
    return get_minmax_impl(data, 1, length, previous);
}

int main(void)
{
    int foo[] = { 12, 484, 487, 1, 500 };
    minmax_t result = get_minmax(foo, sizeof(foo) / sizeof(*foo));
    printf("Min: %d\tMax: %d\n\n", result.min, result.max);
}

关于c - 如何在C中使用结构和递归查找数组中的最大值和最小值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54890766/

10-13 06:59