How to Find Second Maximum Number from Array without Sorting in Java

Find Second Maximum Number from Array without Sorting in Java

In this example, We will show you how to find second maximum number form array without sorting in Java. The example has been tested and output has been shared in the post.

Example Program

package com.dineshkrish;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class FindMax {

	public static void main(String[] args) {
		
		int[] values = {20, 10, 40, 60, 30, 50, 70, 80, 100, 90};
		
		int firstMax = values[0];
		int secondMax = values[0];

		for(int i=0;i<values.length;i++) {
			
			if(firstMax < values[i]) {
				
				firstMax = values[i];
				
				secondMax = firstMax;
				
			} else if(secondMax > values[i]) {
				
				secondMax = values[i];
			}
		}
		
		System.out.println("First Maximum Number : "+firstMax);
		
		System.out.println("Second Maximum Number : "+secondMax);
		
	}
}

Output

First Maximum Number : 100
Second Maximum Number : 90