简体   繁体   中英

Finding index of minimum value in array, USING min(a,b)

Given a task of finding the index of a minimum value in an array, simply looping over, storing the index of smallest value so far and updating it with

min_index = arr[i] < arr[min_index] ? i : min_index;

is simple.

However, we were given the same task, however, we were specified that we MUST use the min(a, b) function.

This could work:

min_index = min(arr[i], arr[min_index]) == arr[i] ? i : min_index;

However, numbers we were dealing with were floats with unknown precision.

I don't think there is anything wrong with your solution for an array of floating-point elements (I assume that there are no NaNs). std::min returns a reference to its argument with a lower value (which is defined for non-nan FP numbers). Thus std::min(arr[i], arr[min_index]) :

  1. either returns a reference to arr[i] if it is less or equal to arr[min_index] ,
  2. or, returns a reference to arr[min_index] , if this is greater than arr[i] .

In 1., when you compare the result of std::min with arr[i] , you are comparing two very same FP objects, which is guaranteed to be evaluated ot true .

In 2., you are comparing two FP objects with different values, which is guaranteed to be evaluated to false .

Therefore, I think your solution works well.

Just be aware that rounding errors outside of your this solution can seemingly break it. Consider the following example:

float arr[3] = { 1.0f / 3.0f, 0.33333334, 2.0f };
size_t min_index = 0;
for (size_t i = 1; i < 3; i++)
   min_index = std::min(arr[i], arr[min_index]) == arr[i] ? i : min_index;
std::cout << min_index;

1/3 is the smallest number, but this printed out 1 in my experiment , since what your code is comparing is a computer representation of 1.0f/3.0f with a computer representation of 0.33333334 , which both are subjects of rounding. Consequently, the numbers actually stored in arr , are different.

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    cin>>n;
    float arr[n];
    float min_index = 0;
    float mini = 0;


    for(int i=0; i<n; i++)
    {
        cin>>arr[i];
    }

    mini = arr[0];

    for(int i=0; i<n; i++)
    {
        mini = min(arr[i], mini);
    }

    for(int i=0; i<n; i++)
    {
        if(arr[i] == mini)
            min_index = i;
    }

    cout<<min_index<<endl;

    return 0;
}

working fine with float! could u be more specific about ur precision?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM