Reputation: 69
Given is:
N
.Find an algorithm that:
K
-th smallest array element.N
log N
) and a space complexity of O(log N
).Upvotes: 6
Views: 1468
Reputation: 2303
You can take the parameterization approach:
Since we have k
specified in the problem, we can treat it as a constant, thus space of O(k
log N
) should be acceptable.
k
partitions of equal length (O(1) time and O(k
log N
) space to store the partition borders because each key should only require log N
space)N
) time and O(k
log N
) space to store the smallest elementsk
) time)Since there's room for more cycles in there, there's probably a better way to do it. Also note that this would perform very poorly on an array that is sorted...
Upvotes: 0
Reputation: 5196
Don't construct partitions. Describe what the partitions are (in constant space), and recursively select on this.
Each subarray that quickselect recurses into can be described by its bounds (min and max element values, not their indexes). Iterating over a subarray so described requires O(n) comparisons, which are made at every recursion level, up to the same depth as in quicksort: O(log n) in the average case.
Quicksort also makes O(n) comparisons at every recursion level, while ordinary permuting quickselect makes O(n) comparisons in total in the average case (because it always recurses into only one partition).
Here's a sample implementation for distinct elements with an ordinary quickselect implementation for comparison.
Upvotes: 2
Reputation: 2281
minimum
and maximum
element.pivot
between minimum
and maximum
(exclusive).pivot
(numSmallerEqual
) and the number of elements greater than pivot
(numBigger
).
numSmallerEqual
, set maximum
=pivot.minimum
=pivot.maximum
- minimum
)==0, output minimum
, terminate.maximum
- minimum
)==1
numSmallerEqual
, output minimum
.maximum
.EDIT: Corrected the error pointed out by lVlad, still not tested.
Upvotes: 2
Reputation: 30969
Treat the problem as something analogous to Quicksort. Given an element in the array, you can get its rank in O(n) time and O(lg n) space. You can use binary search to find an element with a given rank in O(lg n) iterations of that, for a total of O(lg n) space and O(n lg n) time.
Upvotes: 2