Java Program to find max two numbers in an array
Description
In many java interviews especially for freshers, it is asked to write program to find max two numbers from a given array.This kind of program is good to check the programming sense as this program does not use any inbuilt java sorting functions or predefined data structures or collections.It simply uses java iterations and programming sense to swap in between the numbers and find the solution.Following is the implementation.
MaxNumbers.javapackage com.devglan; public class MaxNumbers { public void findTwoMaxNumbers(int[] array){ int maxOne = 0; int maxTwo = 0; for(int num : array){ if(maxOne < num){ maxTwo = maxOne; maxOne =num; } else if(maxTwo < num){ maxTwo = num; } } System.out.println("First Max Number: " + maxOne); System.out.println("Second Max Number: " + maxTwo); } public static void main(String a[]){ int num[] = {6,9,80,56,90,1}; MaxNumbers maxNumber = new MaxNumbers(); maxNumber.findTwoMaxNumbers(num); } }
Explanation
Click to Suggest Your Own Explanation
Take two variables and initiliaze them with zero.Iterate through each element of the array and compare each number against these two number. If current number is greater than maxOne then maxOne = number and maxTwo = maxOne. Otherwise if it only greater than maxTwo then we only update maxTwo with current number.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.