Find Smallest and Largest Element in an Array in Java

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.

1. Introduction to Problem

Let’s say we have an array of numbers.

 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.

Smallest number : 12
Largest number: 343

2. Algorithm

  • Initialize two variable largest and smallest with arr[0]
  • Iterate over array
    • If current element is greater than largest, then assign current element to largest.
    • If current element is smaller than smallest, then assign current element to smallest.
  • You will get smallest and largest element in the end.

3. Implementation

Here is implementation for finding smallest and largest element in an Array.

/*
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); 
 }
}

When you run above program, you will get below output:

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).

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.