Given an unsorted array a[0], a[2], ..., a[n-1], whose elements are not necessarily distinct, we need to find the k-th (k>0) minimal (maximal) element.
The problem is nothing but to return the maximal element of the array when k=1. A typical method to solve such a problem is to use a variable minVar to record the value of a[0], and set the value to be the value of a[i] if a[i]<minVar. The variable minVar will be returned until i>n-1.
This method can be generalized to find the k-th minimal element. We use a new array kSmall[0, ..., k-1] of size k to store k smallest elements of the sub-array from a[0] to a[i]. We compare a[i+1] with elements of the subarray. Then, we may have the following 2 cases:
(1) The new array is not full. Then add the element to the new array to a proper position (Binary search tree method).
(2) The new array is full. Then, we have
(a) if a[i+1]>kSmall[k-1], move to a[k+2].
(b) Otherwise, discard kSmall[k-1] and insert a[i+1] to the proper position in kSmall[0, ..., k-1] by using Binary search tree method.
The element kSmall[k-1] is just what we need after all elements of a[0, ..., n-1] have been examined.
For the case when k=2, we has a differenet approach which is in-place and does not require extra memory allocation. After we build a min-heap based on an unsorted array, the first element is the smallest element of the array. Moreover, one of the a[1] and a[2] is the second minimal element of the array. This is because a[1] and a[2] are roots of two subtrees of the heap, then they are the smallest elements of the two subtrees. Then the smaller element of a[1] and a[2], e.g., a[1], must be smaller than every element in the subtree rooted on a[2]. Then, a[1] is the 2nd minimal element of a[0, ..., n-1].
Please note that the larger element of a[1] and a[2] may not be the 3rd smallest element of the array, since a[2] may be larger than some element in the subtree rooted on the other element.