How to find the smallest and largest element in an array?

--

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)

--

--

Sushant Gaurav
Sushant Gaurav

Written by Sushant Gaurav

A pragmatic programmer 👨🏻‍💻 with a sarcastic mind 😉 who loves travelling and food :)

No responses yet