As a learning lesson, this example could be improved:
First, there's a bug in that it doesn't handle cases like [2, 5, 10, 9, 10, 7] where the numbers aren't unique. (I double-checked, uniqueness was not part of your Params description above.) In that case, the code above will return 9, even though it's clearly not the second-largest.
Second, if you fix that by using >= in the first test, the second one isn't even needed. The storing of second in the first test takes care of the second largest, even if there's only one element in the array.
As a learning lesson, this example could be improved:
First, there's a bug in that it doesn't handle cases like
[2, 5, 10, 9, 10, 7]
where the numbers aren't unique. (I double-checked, uniqueness was not part of your Params description above.) In that case, the code above will return 9, even though it's clearly not the second-largest.Second, if you fix that by using
>=
in the first test, the second one isn't even needed. The storing ofsecond
in the first test takes care of the second largest, even if there's only one element in the array.So the
for
loop could be simplified to just: