I have this:
int[] tal = {3, 8, 5, 8, 2, 3, 9, 12, 21};
int max=tal[0];
for(int i=0;i<tal.length;i++){
if(tal[i]>5){
max=tal[i];
}
}
System.out.println("Biggest: "+ max);
Im reading Java, how can i make print out the next biggest number
Assuming you don’t want to sort the array, as some of the other answers suggest:
Credits to @Andreas_D for the original code, which I modified to fix a problem.
There are some extra conditions you may need to check for; for example, the array needs to contain at least two elements for a valid result. Realistically, I would only opt for a solution such as this if you expect to be dealing with large inputs, and if you always need the second largest (or largest) number. Otherwise, just go with the Arrays.sort solution.
Because I’m mostly a .NET guy, I’ll show you the Pex explorations of this implementation (Pex is a tool which looks for edge cases in your code):
alt text http://subbot.net/personal/external/stackoverflow/pex-second-largest.png
Andreas contributed a modification, which changes the behavior when it comes to duplicate entries:
More Pex explorations after the modification:
