Maximum and minimum algorithm optimization

     Originally published in:

 

 

     It rains heavily in Shenzhen on Sundays.

 

 

      Let’s look at a simple problem today, which is to find the maximum and minimum values ​​at the same time. The specific problems and requirements are as follows:

      To find the maximum and minimum values ​​of the array, the number of comparisons required is O(1.5n).

 

       Let's first look at the ordinary intuitive solution:

package main

import "fmt"

func getMinMax(a []int) (int, int){
  if len(a) == 0 {
    // 异常处理
  }
  
  min, max := a[0], a[0]
  
  for _, v := range a {
    if v < min {
      min = v
    }
    
    if v > max {
      max = v
    }
  }
  
  return min, max
}

func main() {
  fmt.Println(getMinMax([]int{3, 2, 4, 1, 5, 9, 6, -1}))
}

       Result: -1 9

        

      It can be seen that the order of magnitude of the number of comparisons in the program is O(2n). In actual development, this can often meet the requirements, and it is also an intuitive and easy-to-understand solution, and the code is more readable.

 

      Let's take a look at the specific idea of ​​the above code: as shown in the figure below, after traversing the first two elements, the values ​​of min and max are 2 and 3 respectively. In the comparison with the next 4 and 1, min should be compared twice. max needs to be compared 2 times, which is 4 times in total.

      

      However, if the number of comparisons of the target is optimized to O(1.5n) according to the requirements of the problem, how should we proceed? We see that if we first compare 4 and 1, and get the larger 4 and the smaller 1, then the rest only needs to compare min with 1, and max with 4, and the total number of comparisons is only 3 times, reducing useless comparisons, as shown below:

 

      It can be seen that the idea of ​​optimization is to group the elements in pairs, and the number of comparisons has been optimized from O(2n) to O(1.5n). Now that the idea is clear, the code implementation is relatively simple. Go into details.

 

      This article is relatively simple, the key is still the idea, let's talk about it first.

 

Guess you like

Origin blog.csdn.net/stpeace/article/details/109541157