简体   繁体   English

表中的最小值和最大值

[英]Min and Max value in Table

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;
  }
 }

The easiest method to get min and max is probably to sort them, but The code that you wrote is best for performance. 获取min和max的最简单方法可能是对它们进行排序,但是您编写的代码最适合于性能。 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. 此代码将进行较少的比较,但不一定会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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