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

后端 未结 18 844
日久生厌
日久生厌 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:42

    If

    1. The array is not sorted
    2. Finding the min and max is done simultaneously

    Then there is an algorithm that finds the min and max in 3n/2 number of comparisons. What one needs to do is process the elements of the array in pairs. The larger of the pair should be compared with the current max and the smaller of the pair should be compared with the current min. Also, one needs take special care if the array contains odd number of elements.

    In c++ code (borrowing some code from Mehrdad).

    struct MinMax{
       int Min,Max;
    }
    
    MinMax FindMinMax(int[] array, int start, int end) {
       MinMax  min_max;
       int index;
       int n = end - start + 1;//n: the number of elements to be sorted, assuming n>0
       if ( n%2 != 0 ){// if n is odd
    
         min_max.Min = array[start];
         min_max.Max = array[start];
    
         index = start + 1;
       }
       else{// n is even
         if ( array[start] < array[start+1] ){
           min_max.Min = array[start];
           min_max.Max = array[start+1];
         }
         else{
           min_max.Min = array[start+1];
           min_max.Max = array[start];
         }
         index = start + 2;
       }
    
       int big, small;
       for ( int i = index; i < n-1; i = i+2 ){
          if ( array[i] < array[i+1] ){ //one comparison
            small = array[i];
            big = array[i+1];
          }
          else{
            small = array[i+1];
            big = array[i];
          }
          if ( min_max.Min > small ){ //one comparison
            min_max.Min = small;
          }
          if ( min_max.Max < big ){ //one comparison
            min_max.Max = big;
          }
       }
    
       return min_max;
    }
    

    It's very easy to see that the number of comparisons it takes is 3n/2. The loop runs n/2 times and in each iteration 3 comparisons are performed. This is probably the optimum one can achieve. At this moment, I cannot point to a definite source of that. (But, I think I have seen a proof of that somewhere.)

    The recursive solution given by Mehrdad above, probably also achieves this minimal number of comparisons (the last line needs to be changed). But with the same number of comparisons an iterative solution will always beat a recursive solution due to overhead in the function call as he mentioned. However, if one only cares about finding min and max of a few numbers (as Eric Belair does), no one will notice any difference in todays computer with any of the approaches above. For a large array, the difference could be significant.

    Though this solution and the solution given by Matthew Brubaker has O(n) complexity, in practice one should carefully asses the hidden constants involved. The number of comparisons in his solution is 2n. The speedup gained with the solution with 3n/2 comparisons as opposed to 2n comparisons would be noticeable.

    0 讨论(0)
  • 2020-11-27 03:42

    There are a number of ways this can be done.

    1. Brute force. Linear search for both min and max separately. (2N comparisons and 2N steps)
    2. Iterate linearly and check each number for both min and max. (2N comparisons)
    3. Use Divide and conquer. (Between 2N and 3N/2 comparisons)
    4. Compare by pairs explained below (3N/2 Comparisons)

    How to find max. and min. in array using minimum comparisons?


    If you are really paranoid about speed, runtime & number of comparisons, also refer to http://www.geeksforgeeks.org/maximum-and-minimum-in-an-array/

    0 讨论(0)
  • 2020-11-27 03:43

    Math.max() is actually as3 code compiled to AVM2 opcodes, and as such is not more "native" than any other as3 code. As a consequence, it is not necessarily the fastest implementation.

    Actually, given that it works on Array type, it is slower than carefully written code usign Vector:

    I did a quick benchmark comparison of several naive Vector and Array implementations of Math.max, using gskinner's PerformanceTest (Vector and Array being filled with identical random Numbers). The fastest Vector implementation appeared to be more than 3x faster than Math.max with recent AIR SDK/release player (flash player WIN 14,0,0,122 RELEASE, compiled with AIR SDK 14):

    average 3.5 ms for 1,000,000 values, compared to Math.max() average of 11ms :

    function max(values:Vector.<Number>):Number
    {
        var max:Number = Number.MIN_VALUE;
        var length:uint = values.length;
        for (var i:uint = 0; i < length ; ++i)
            if (values[i] > max)
                max = values[i];
        return max;
    }
    

    Conclusion is that if you are concerned by performance, you should use Vector over Array anywhere you can in the first place, and not always rely on default implementations, especially when they force the use of Array

    PS:same implementation with a for each() loop is 12x slower ...!

    0 讨论(0)
  • 2020-11-27 03:43

    Below is Solution with o(n):-

    public static void findMaxAndMinValue(int A[]){
        int min =0, max = 0;
        if(A[0] > A[1] ){
            min = A[1];
            max = A[0];
        }else{
            max = A[1];
            min = A[0];
        }
        for(int i = 2;i<A.length ;i++){
            if(A[i] > max){
                max = A[i];
            }
            if(min > A[i]){
                min = A[i];
            }
        }
        System.out.println("Maxinum Value is  "+min+" & Minimum Value is  "+max);
    }
    
    0 讨论(0)
  • 2020-11-27 03:45

    You have to loop through the array, no other way to check all elements. Just one correction for the code - if all elements are negative, maxValue will be 0 at the end. You should initialize it with the minimum possible value for integer.
    And if you are going to search the array many times it's a good idea to sort it first, than searching is faster (binary search) and minimum and maximum elements are just the first and the last.

    0 讨论(0)
  • 2020-11-27 03:51

    Please take into account that sorting the array will only be faster that looping up to certain size of the array. If your array is small (and it will be like that any time) then your solution is perfectly fine. But if it might get too large you should use a conditional to use the sort approach when the array is small, and the normal iteration when it is too large

    0 讨论(0)
提交回复
热议问题