Table of Contents
If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.
In this post, we will see how to find smallest and largest element in an array.
When you run above program, you will get below output:
1. Introduction to Problem
Let’s say we have an array of numbers.
1 2 3 |
int arr[] = new int[]{12,56,76,89,100,343,21,234}; |
Our goal is to find out smallest and largest number in the array.
1 2 3 4 |
Smallest number : 12 Largest number: 343 |
2. Algorithm
- Initialize two variable
largest
andsmallest
with arr[0] - Iterate over array
- If current element is greater than
largest
, then assign current element tolargest
. - If current element is smaller than
smallest
, then assign current element tosmallest
.
- If current element is greater than
- You will get
smallest
andlargest
element in the end.
3. Implementation
Here is implementation for finding smallest and largest element in an Array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/* Java program to Find Largest and Smallest Number in an Array */ public class FindLargestSmallestNumberMain { public static void main(String[] args) { //array of 10 numbers int arr[] = new int[]{12,56,76,89,100,343,21,234}; //assign first element of an array to largest and smallest int smallest = arr[0]; int largest = arr[0]; for(int i=1; i< arr.length; i++) { if(arr[i] > largest) largest = arr[i]; else if (arr[i] < smallest) smallest = arr[i]; } System.out.println("Smallest Number is : " + smallest); System.out.println("Largest Number is : " + largest); } } |
1 2 3 4 |
Largest Number is : 343 Smallest Number is : 12 |
4. Time Complexity
Time Complexity of above program is o(n). This is because we iterated over the array once.
5. Conclusion
In this article, we covered basic program to find smallest and largest element in the array. We have also analyzed time complexity which is o(n).
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.