In this article we are going to discuss a problem from arrays; this is one of the most commonly asked interview question of today. Write a program to find top two maximum numbers in an Array, without sorting the array and without using any collection.

Write a program to find top two maximum numbers in an Array, without sorting the array and without using any collection.

e.g. if {4, 5, 7, 11, 9, 13, 8, 12} is an given array, than find out two max numbers 12 and 13 in this case, you can't sort the array and you can't use any collection. Do this in a single loop only.

We can find the easiest solution by iterating over the array and holding two max values in two different variables as shown in the example below.
package com.tbNext.byexample;

public class TBTopTwoNumbers {
	public static void main(String[] args) {
		int[] arr = { 2, 3, 5, 2, 6, 7, 2, 5, 8 };
		TBTopTwoNumbers topTwoNumbers = new TBTopTwoNumbers();
		topTwoNumbers.topTwoNumbers(arr);
	}

	private void topTwoNumbers(int[] arr) {
		int max = 0;
		int secondMax = 0;

		for (int i : arr)
			if (i > max) {
				secondMax = max;
				max = i;
			} else if (i > secondMax)
				secondMax = i;

		System.out.println("Max: " + max + " Second Max: " + secondMax);
	}
}


Output:

Max: 8 Second Max: 7


That'?s it, we saw how to write a program to find top two maximum numbers in an Array, without sorting the array and without using any collection.. In upcoming articles we will see more about Java and Related programming problems and solutions.
  • By Techburps.com
  • May 9, 2015
  • Programming