Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding smallest value in an array most efficiently

Tags:

c++

arrays

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

like image 207
Muhammad Akhtar Avatar asked Jun 25 '09 07:06

Muhammad Akhtar


People also ask

What is the time complexity to find the smallest element?

We have to find the smallest/ minimum element in an array. The time complexity to solve this is linear O(N) and space compexity is O(1).

What is the best algorithm to find the maximum and the minimum numbers in an array?

We traverse the array from i = 1 to n - 1 and compare each element with min and max. If (X[i] < min): We have found a value smaller than minimum till ith index. So update min with X[i] i.e min = X[i]. else If(X[i] > max): We have found a value greater than maximum till ith index.


1 Answers

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.


Pseudo-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 

The above is wrapped in the algorithm header as std::min_element.


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.

like image 196
GManNickG Avatar answered Sep 19 '22 09:09

GManNickG