How to find the smallest and largest element in an array?
Jan 1, 2022
Let's discuss 2 ways to find a largest and smallest elements of an array:
Problem — Find the smallest and largest elements in an array A of size n.
Example:
A = { 8 ,10 , 2 ,15 ,13 ,-1 }
Smallest = -1
Largest = 15
Approach 1-
Scan the entire array and update small and large variable accordingly.
Code:
Output :
Smallest Element = 1
Largest Element = 15
Time Complexity = O(n) and Space Complexity = O(1)
Approach 2 -
The lesser scan approach :
Scan in pairs and update the small and large element
Code:
Output :
Smallest Element = -8
Largest Element = 15
Time Complexity = O(n) and Space Complexity = O(1)