0
$\begingroup$

Say I have 3 simple tasks, to find the min, the max, and the average of an array of numbers.

A modular approach would be to write one function for each, thus iterating over the array thrice. However, that seems wasteful when all the information can be collected in a single iteration.

I understand that both approaches take 3n time but am wondering if one approach is better than the other in the general case and why.

$\endgroup$
1
$\begingroup$

Collecting the information in a single iteration would be way better, but you'll only notice the difference if your array contains a large number of numbers. On a small scale, it just won't make a difference.

| cite | improve this answer | |
$\endgroup$
0
$\begingroup$

You can use a function to compute all of them. You can find in this post the implementation of min and max with each other using 3n/2 - 2 comparison instead of 2n. Also, summing the values in the meanwhile of iterating over the whole of the data. It's the minimum number of iteration and comparison over data.

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ That is a good approach for the example of min, max, and average. What about the general case? $\endgroup$ – wsaleem Feb 16 '19 at 17:44
  • $\begingroup$ @wsaleem You can't talk about it in general case $\endgroup$ – OmG Feb 16 '19 at 17:55
0
$\begingroup$

Usually you should do whatever code is more readable. If you need to find min, max, and sum or average, then having a single function that does exactly what it needs to do is the simplest and most readable approach. It's all in one place. If I need to check what the function does, I don't have to hunt around in different places. So usually, you should have one function.

If performance is more important than readability, then you should also have one function. You will read n array elements instead of 3n. You can determine min and max simultaneously with 1.5n comparison instead of 2n. On multi-issue CPUs where performance is limited by latency, you have 1x latency instead of 3x latency, so your code could be up to 3 times faster.

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ Aren't atomic functions more readable and reusable? $\endgroup$ – wsaleem Feb 16 '19 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.