Algorithm to find the smallest and largest number in a given list

Published on November 17, 2021
Last updated November 17, 2021

Write an algorithm to find the smallest and largest number in a given list.

Algorithm

Algorithm SmallLarge(A,n)
{
    small = A[0];
    large = A[0];
    for i = 1 to n-1 do
    {
        if(A[i] < small)
            small = A[i];
        if(A[i] > large)
            large = A[i];
    }
    write small, large;
}

In the algorithm we will declare two variables small and large and initialize them with the first element of the list. Then we will iterate through the list and check if the current element is smaller than small or larger than large. If it is smaller than small then we will update small with the current element. If it is larger than large then we will update large with the current element.

After the loop is completed we will print the values of small and large.

These will be the smallest and largest number in the list.

Following the algorithm we can write the code in a language of our choice.



Tags :