Java Program to find max two numbers in an array

Java Program to find max two numbers in an array thumbnail
29K
By Dhiraj Ray 01 January, 2018

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.java
package 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

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.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.