Algorithms — Min and Max

Sejan Miah
killingMeSwiftly
Published in
3 min readAug 17, 2017

In today’s blog post, let’s go over a recent algorithm problem I solved without any helper/high order functions. I was told to find the minimum and maximum value in an array without the functions min and max.

The first thing I needed to do after writing the method signature was guard for user inputs where the array of integers did not contain 2 or more numbers. There’s really no point in even using this function if the user inputs an array with just one integer value.

Then we need to create placeholder variables that will contain the minimum and maximum values for us. Currently, set both of these to the first element in the array. We will be using the first element in our array as the reference for both the maximum and minimum values, don’t worry these values are subject to change.

Now we will delve into our for-loop, but before we do let’s really think about what we are trying to accomplish with these variables we created. We are going to compare all the elements in our for loop with our variables min and max. Whichever element is smaller should become the new min value and whichever element is larger should become the larger max value.

Why don’t we put a print statement in our loop as well to see how the values will be changing? Finally, you return (min, max) and this should be returning for you the correct values.

Let’s take a look at our function holistically now with all the code in its entirety. You’ll see that the values for min and max are continuously changing until we complete our for loop, at which time we have finally altered the variable to reference the right element in the loop.

It’s easy to become dependent on so many methods that are accessible to us, but it is even more important to truly understand the inner working of each method or framework for that matter. I hope this basic algorithm solution will help you in your future coding endeavors.

--

--