Skip to content

Latest commit

 

History

History
36 lines (25 loc) · 1.06 KB

find_the_smallest_element_in_an_array.md

File metadata and controls

36 lines (25 loc) · 1.06 KB

Find the Smallest Element in an Array

To find the smallest element in an array, iterate through the array and keep track of the smallest element.

Algorithm:

  1. Initialize a variable to store the smallest element with a large value (e.g., Infinity).
  2. Iterate through the array and compare each element to the current smallest value.
  3. Update the smallest value whenever a smaller element is found.
  4. Return the smallest value.

Example:

function findSmallest(arr) {
    let smallest = Infinity;

    for (const num of arr) {
        if (num < smallest) {
            smallest = num;
        }
    }

    return smallest;
}

// Example usage
console.log(findSmallest([5, 3, 8, 1, 6])); // Output: 1
console.log(findSmallest([7, 4, 9, 2])); // Output: 2

This method has a time complexity of O(n), where n is the length of the array.

Tags: basic, JavaScript, Arrays, Algorithm