Find Min & Max Value in an Unsorted List of Integers in Java

In this post, we will see how to find min & max value in an unsorted list of integers in Java without using Java 8 Stream.


 

1. Naive

Here’s naive (but efficient) way of finding find min & max value in an unsorted list where we check against all values present in the list and maintain minimum & maximum value found so far.

Min

Download   Run Code

Max

Download   Run Code

 

2. Collections.max()

Collections.min() method returns the minimum element in the specified collection and Collections.max() returns the maximum element in the specified collection, according to the natural ordering of its elements.

Min

Max

Both these methods iterates over the entire list, hence they requires time proportional to the size of the list.

 

3. Sorting

This is least efficient approach but will get the work done. The idea is to sort the list in natural order, then the first or last element would be the minimum and maximum element respectively. Below’s implementation in Java:

Min

Download   Run Code

Max

Download   Run Code

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz