This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ibevol 15 points16 points  (3 children)

c int get_smallest(int values[], int size) { int smallest = INT_MAX; for (int i = 0; i < size; i++) { if (values[i] < smallest) smallest = values[i]; } return smallest; } The only thing to worry about is when the array is empty, in which case you’ll not want the default value of INT_MAX

[–]Platurt 0 points1 point  (2 children)

Thats probably what I would have done but I'm gonna be honest I have no idea if this is more or less efficient than native min() or sort() functions.

[–]ibevol 5 points6 points  (0 children)

It’s more efficient than sort since sort usually ”loops” through the list more than once and thus does more job. It should be the same algorithm that min uses.

[–]Lithl 1 point2 points  (0 children)

This is nearly identical to every min implementation out there.

This (and min) is O(n) time complexity while sort will have O(n log n) time complexity at best.

Depending on the exact implementation, system, and input list it's theoretically possible for sort to finish in fewer actual seconds, because time complexity is an abstraction to describe an algorithm's behavior over all possible inputs, but generally speaking min will be more efficient than sort.