Suppose I have an unsorted integer array a[]
with length N
.
Now I want to find the k-th smallest integer within a given interval a[i]-a[j]
(1 <= i <= j <= N
).
Ex: I have an array a[10]={10,15,3,8,17,11,9,25,38,29}
.
Now I want to find the 3-rd smallest element within a[2]-a[7]
interval.
The answer is 9.
I know this can be done by sorting that interval. But this costs O(Mlog(M))
(M = j - i + 1
) time. Also, I know that, this can be done by segment tree, but I can't understand how to modify it to handle such query.
Asked
Active
Viewed 1,056 times
2

OmG
- 18,337
- 10
- 57
- 90

Dharsam1990
- 121
- 10
-
1Have a look at [quickselect](https://en.wikipedia.org/wiki/Quickselect) – toasted_flakes Dec 01 '13 at 10:00
1 Answers
0
You can use Quickselect, a modification of Quicksort to find the kth smallest/largest value in a list. Let's just assume that you're trying to do this for the entire array, for the sake of simplicity (note that there is no difference).
Essentially you use quicksort, but only use one recursive call instead of two. Once your pivot it placed, you only need to call quicksort for one of the partitions, depending on the placement of pivot. This is O(N2), but average case of O(N). If you use random pivots, it's pretty much always going to be O(N).

Steve P.
- 14,489
- 8
- 42
- 72
-
I understood... Problem is if the interval size is large(say j-i=10^5) and the number of queries are large (say m=1000)... Then it takes m*(j-i) i.e. almost 10^8 computations... so I was asking if we can make it for each query it takes log(j-i) computations... then you will need a segment tree or any related augmented data structure to do so... – Dharsam1990 Dec 01 '13 at 14:06