You cannot know the answer if you do not look at each element at least once. However, if that is not your problem, you can use a binary search tree:
In computer science, a binary search tree (BST), which can sometimes be called an ordered or sorted binary tree, is a node-based binary tree data structure that has the following properties: [1]
The left subtree of the node contains only nodes with keys smaller than the node key. The right subtree of the node contains only nodes with keys greater than or equal to the node key. Both left and right subtrees should also be binary search trees.
Source: http://en.wikipedia.org/wiki/Binary_search_tree
How do you find the 2nd largest item?
Well, from how BST is formed, you know that the largest element is the right-most (starting from the root of the node, take the right child until you have nowhere else to go).
Now, how to determine the second largest?
Well, this may not be the most effective approach, but allow it in cases:
The largest node is the root of the tree and has no children. There is no 2nd largest element in your tree, because there is only node in your tree
The largest node is the root of the tree (does not have the right child) - the second largest element is the largest element in the left subtree
The largest element is not the root of the tree, not the leaf (has a left child) - the second largest element is its left child
The largest element is not the root of the tree, but the leaf (has no children) - the second largest element - its parent
I am sure that now you can define a template and a simple algorithm: D
source share