HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMajor

Min / Max function of 1D array in C / C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
minmaxfunctionarray

Problem

Due to software constraints, I cannot use the standard libraries, `, , templates, inline, or Boost. I am also using standard C (ISO C99) such that array` is not a reserved keyword like it is in Visual Studio.

Is this the "best" possible implementation of a min function? This needs to be robust and fast. Is there a more efficient C++ implementation?

double min(double* array, int size){
    // returns the minimum value of array
    static double val = array[0];
    for (int i = 1; i < size; ++i){
        val = val <= array[i] ? val : array[i];
    }
    return val;
}

Solution

It's not quite the best. There's some things IMHO that is hindering its performance and usefulness.

There's no point in declaring val as a static variable. In fact, you've killed any chance of it being usable in multi-threaded programs.

The body of the loop is performing an assignment in every single iteration when it doesn't need to. If you want it to be its best, you should only be doing so when it is required.

Your overall structure is fine, assuming we can expect well-formed inputs where array is nonempty and size is positive, I'd just change it so it's more like this:

double min(const double *arr, size_t length) {
    // returns the minimum value of array
    size_t i;
    double minimum = arr[0];
    for (i = 1; i  arr[i]) {
            minimum = arr[i];
        }
    }
    return minimum;
}

Code Snippets

double min(const double *arr, size_t length) {
    // returns the minimum value of array
    size_t i;
    double minimum = arr[0];
    for (i = 1; i < length; ++i) {
        if (minimum > arr[i]) {
            minimum = arr[i];
        }
    }
    return minimum;
}

Context

StackExchange Code Review Q#5143, answer score: 20

Revisions (0)

No revisions yet.