Find smallest and largest element in an array | faceprep

Find smallest and largest element in an array | faceprep

This article discusses the program used to find the smallest and largest element in an array. Given an array, the objective of the program will be to find the largest and smallest elements.


Find the Smallest and Largest Element in an Array

Method 1: Traverse the array iteratively and keep track of the smallest and largest element until the end of the array.

Method 2: Traverse the array recursively and keep track of the smallest and largest element until the end of the array.

Method 3: Sort the array using STL and return the first element as the smallest element and the last element as the largest element.

For example, consider the array.

arr = {1, 2, 3, 4, 5}

Smallest element : 1

Largest element : 5

find smallest and largest element in an array

Algorithm to find the smallest and largest numbers in an array

  1. Input the array elements.
  2. Initialize small = large = arr[0]
  3. Repeat from i = 2 to n
  4. if(arr[i] > large)
  5. large = arr[i]
  6. if(arr[i] < small)
  7. small = arr[i]
  8. Print small and large.

Iterative program to find the smallest and largest element in an array

@@coding::1@@

Time complexity: O(n)

Recursive program to find the smallest and largest element in an array

@@coding::2@@

Time complexity: O(n)


Find the Smallest and Largest Element in an Array 

Program to find the smallest and largest element in an array using STL?

@@coding::3@@

Time complexity: O(n log n)


Suggested Articles




Find the Smallest and Largest Element in an Array


c