min in array

Finding the minimum value in an array is a common task for many programming applications. There are a few different ways of doing it, depending on the language you're using. In this answer, I'll be discussing two of them, the iterative and the recursive approach.

Firstly, let's start with the iterative approach. This involves looping through the array and keeping track of the smallest value that we come across. Every time we loop through, we check if the current value is smaller than the last smallest value. If it is, then we update the smallest value. Once we've looped through the entire array, the smallest value is whatever is stored in our smallest variable.


    function findMinIterative(arr) {
        // Set min to the first element in arr
        let min = arr[0];
    
        // Loop through the array
        for (let i = 0; i < arr.length; i++) {
            // if the current element is less than min
            if (arr[i] < min) {
                // Update min to the current element
                min = arr[i];
            }
        }
    
        // Return min
        return min;
    }
    

Secondly, let's move on to the recursive approach. This is a bit more complicated, but it's still quite easy to understand. The recursive approach involves passing in the array and the current smallest value into a recursive function. This function should then check if the current element is smaller than the smallest value, and if it is, update the smallest value. It should then call itself with the updated smallest value, and the rest of the array. Eventually, the base case will be reached, where the function will return the smallest value.


    function findMinRecursive(arr, min) {
        // Base case, if arr is empty
        if (arr.length === 0) {
            // return min
            return min;
        }
    
        // Get the first element in arr
        let first = arr[0];
    
        // if first is less than min
        if (first < min) {
            // Update min to first
            min = first;
        }
    
        // Call the function again with the rest of the array
        // and the updated min
        return findMinRecursive(arr.slice(1), min);
    }
    

Both of these approaches are fairly simple ways to find the minimum value in an array, and they should work in most programming languages. It's worth noting that the iterative approach is generally more efficient than the recursive approach, as the recursive approach involves a lot of overhead with the function calls.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe