How to find the smallest number in an array?

Photo by Gabriella Clare Marino on Unsplash

Finding the smallest number in an array could be as simple as sorting the array and taking the number at the first index. But would be a very inefficient way doing it.

A better way would be to just assume that the first number is the minimum number. And we are done.

Hold on... That's not right. The probability of getting it correct in this manner is just 1/N, where N is the length of the array. We need something that would work every single time.

We could store the number at the first index in a temporary variable and then we could iterate over the array and check it with every element of the array. If a number is smaller than the value in the temporary variable we store that number in the temporary variable. Once we have iterated over the entire array, we can be sure that the number in the temporary variable is the minimum number.

Let's look at the pseudocode.

FUNCTION FindTheSmallestNumber(numbers):
    smallest = numbers[0]
    FOR number in numbers:
    	IF number < smallest:
            smallest = number
    RETURN smallest

Now that we have discussed the pseudocode, try this problem in Hashjar Arena before moving on to the solution.

Find the smallest number in the given array


Now let's look at how we can implement this in code. Scroll down to find your favorite language. We cover Python, Javascript and Typescript.

Python

def findTheSmallestNumber(numbers):
  smallest = numbers[0]
  for i in range(len(numbers)):
    if(numbers[i] < smallest):
      smallest = numbers[i]
  return smallest

Javascript

function findTheSmallestNumber(numbers) {
  let smallest = numbers[0];
  for(let i = 0; i < numbers.length; i++) {
    if(numbers[i] < smallest) {
      smallest = numbers[i];
    }
  }
  return smallest;
}

Typescript

function findTheSmallestNumber(numbers: number[]): number {
  let smallest = numbers[0];
  for(let i = 0; i < numbers.length; i++) {
    if(numbers[i] < smallest) {
      smallest = numbers[i];
    }
  }
  return smallest;
}

Now that you know how to find the smallest number in an array, can you find the problem in Javascript this code?

Fix the bug in finding smallest number in the given array [JS]

Hashjar

Hashjar