Link copied to clipboard. Share away!

Dissmis

Published on 10 Mar 2020

Program to find the smallest and largest elements in an array is discussed here. Given an array, the task is to find the largest and smallest elements of the 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

- Input the array elements.
- Initialize small = large = arr[0]
- Repeat from i = 2 to n
- if(arr[i] > large)
- large = arr[i]
- if(arr[i] < small)
- small = arr[i]
- Print small and large.

C

C++

Java

Python 3

Output

Enter the number of elements : 5

Input the array elements : 1 2 3 4 5

The smallest element is 1

The largest element is 5

Input the array elements : 1 2 3 4 5

The smallest element is 1

The largest element is 5

**Time complexity:** O(n)

C

C++

Java

Output

Enter size of the array : 5

Input the array elements : 1 2 3 4 5

Smallest element in array is 1

Largest element in array is 5

Input the array elements : 1 2 3 4 5

Smallest element in array is 1

Largest element in array is 5

**Time complexity:** O(n)

C++

Java

Output

Enter size of the array : 5

Input the array elements : 1 2 3 4 5

Smallest element in array is 1

Largest element in array is 5

Input the array elements : 1 2 3 4 5

Smallest element in array is 1

Largest element in array is 5

**Time complexity: **O(n log n)

*Recommended Programs*

If you have any feedback about this
article and want to improve this, please write to **enquiry@faceprep.in**

×