This post is about writing a Java program to find the top two numbers (largest and second largest) in the given array.
Condition here is that you should not be using any inbuilt Java classes or methods (i.e. Arrays.sort) or any data structure.
Solution to find largest and second largest number
Logic here is to have two variables for first and second number and iterate the array. Compare each array element with the first number if first number is less than the array element then assign existing first number to second number and array element to the first number.
If first number is greater than the array element then check if second element is less than the array element, if yes then assign array element to the second number.
Java code
public class FindTopTwo {
public static void main(String[] args) {
int numArr[] = {2, 5, 14, 1, 26, 65, 123, 6};
int firstNum = 0;
int secondNum = 0;
for(int i = 0; i < numArr.length; i++){
if(firstNum < numArr[i]){
secondNum = firstNum;
firstNum = numArr[i];
}else if(secondNum < numArr[i]){
secondNum = numArr[i];
}
}
System.out.println("Top two numbers : First - "
+ firstNum + " Second " + secondNum);
}
}
Output
Top two numbers : First - 123 Second 65
That's all for this topic Find Largest and Second Largest Number in Given Array - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -