Find the k-th minimal element of an unsorted array

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值