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

后端 未结 18 1000
日久生厌
日久生厌 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 04:00

    This depends on real world application requirements.

    If your question is merely hypothetical, then the basics have already been explained. It is a typical search vs. sort problem. It has already been mentioned that algorithmically you are not going to achieve better than O(n) for that case.

    However, if you are looking at practical use, things get more interesting. You would then need to consider how large the array is, and the processes involved in adding and removing from the data set. In these cases, it can be best to take the computational 'hit' at insertion / removal time by sorting on the fly. Insertions into a pre-sorted array are not that expensive.

    The quickest query response to the Min Max request will always be from a sorted array, because as others have mentioned, you simply take the first or last element - giving you an O(1) cost.

    For a bit more of a technical explanation on the computational costs involved, and Big O notation, check out the Wikipedia article here.

    Nick.

提交回复
热议问题