0
votes

The following code find the max and min value in table.

For the max value (not for the min) , i need also its position.

The compilation is succeded.

I want know if the functional of the code is also correct or if there is an other easy methode.

#define MAX_VALUE 0
#define MIN_VALUE 1
typedef Min_Max_Data
{
  unsigned char Value;
  unsigned char Position;
}Min_Max_Data_t;

Min_Max_Data_t Data;

void Min_Max_Data_Value(unsigned char *Array
                        , unsigned char Min_Max
                        , unsigned char Dim)
  {
   unsigned char i;

    switch (Min_Max)
    {
     case  MAX_VALUE:
     {
     Data.Value = *Array;
     Data.Position = 0;

     for (i = 0; i < Dim; i++)
     {
        if (*(Array + i) > Data.Value)
        {
           Data.Value   = *(Array + i);
           Data.Position = i;
        }
     }
   break;
  }
   case  MIN_VALUE:
   {
     Data.Value = *Array;
     Data.Position = 0;
     for (i = 0; i < Dim; i++)
     {
        if (*(Array + i) < Data.Value)
        {
           Data.Value   = *(Array + i);
        }
     }
    break;
  }
  default:
    break;
  }
 }
1

1 Answers

0
votes

The easiest method to get min and max is probably to sort them, but The code that you wrote is best for performance. However You should look into recursion.

typedef struct {
int Min;
int Max;
}ValuesStruct;

ValuesStruct yourFunction(int[] array, int start, int end) {
    ValuesStruct yourMinMax;
    int index, i;
    int n = end - start + 1;
    if ( n%2 != 0 ){//odd
        yourMinMax.Min = array[start];
        yourMinMax.Max = array[start];
        index = start + 1;
    }
    else{//even
        int max, min;
        if ( array[start] < array[start+1] ){
            yourMinMax.Min = array[start];
            yourMinMax.Max = array[start+1];
            index = start + 2;
        }
        for (i = index; i < n-1; i = i+2 ){
            if ( array[i] < array[i+1] ){
                min = array[i];
                max = array[i+1];
            }
            else{
                min = array[i+1];
                max = array[i];
            }
            if ( yourMinMax.Min > min ) yourMinMax.Min = min;
            if ( yourMinMax.Max < max ) yourMinMax.Max = max; 
        }
        return yourMinMax;
    }
}

This code will take less comparisons, but isn't necessarily faster.