在阵列最有效地查找最小值 [英] Finding smallest value in an array most efficiently

查看:113
本文介绍了在阵列最有效地查找最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有数组中N个值,并把它们中的一个是最小的值。我如何才能最有效地找到最小的价值?

There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently?

推荐答案

如果他们未排序,则不能做很多,但看每个人,这是O(N),当你做你会知道的最小

If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum.


伪code:

small = <biggest value> // such as std::numerical_limits<int>::max
for each element in array:
    if (element < small)
        small = element

奔想起一个更好的方式来我是刚刚初始化小,第一个元素:

A better way reminded by Ben to me was to just initialize small with the first element:

small = element[0]
for each element in array, starting from 1 (not 0):
    if (element < small)
        small = element

以上是裹在算法头作为的的std :: min_element


如果你能保持你的数组排序在添加项目,然后找到这将是O(1),因为你可以保持在最小的前面。

If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front.

这是因为它与数组好得不能再好。

That's as good as it gets with arrays.

这篇关于在阵列最有效地查找最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆