What is the best way to get the minimum or maximum value from an Array of numbers?

后端 未结 18 1080
日久生厌
日久生厌 2020-11-27 03:00

Let\'s say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]

What is the best way to find the minimum or maximum value in that Array?

Right now,

18条回答
  •  悲哀的现实
    2020-11-27 03:41

    Depends on what you call "best." From a theoretical point of view, you cannot solve the problem in less than O(n) in a deterministic Turing machine.

    The naive algorithm is too loop and update min, max. However, a recursive solution will require less comparisons than naive algorithm, if you want to get min, max simultaneously (it isn't necessarily faster due to function call overhead).

    struct MinMax{
       public int Min,Max;
    }
    
    MinMax FindMinMax(int[] array, int start, int end) {
       if (start == end)
          return new MinMax { Min = array[start], Max = array[start] };
    
       if (start == end - 1)
          return new MinMax { Min = Math.Min(array[start], array[end]), Max = Math.Max(array[start], array[end]) } ;
    
       MinMax res1 = FindMinMax(array, start, (start + end)/2);
       MinMax res2 = FindMinMax(array, (start+end)/2+1, end);
       return new MinMax { Min = Math.Min(res1.Min, res2.Min), Max = Math.Max(res1.Max, res2.Max) } ;
    }
    

    The simplest solution would be to sort and get the first and last item, though it's obviously not the fastest ;)

    The best solution, performance-wise, to find the minimum or maximum is the naive algorithm you written (with a single loop).

提交回复
热议问题