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.

Our goal is to find out smallest and largest number in the array.

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.

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

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?

Leave a Reply

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