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

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

    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/

提交回复
热议问题