May. 27th, 2011
sorting to extract a range
May. 27th, 2011 12:20 pmSo, we have 100500 records; we need to take, say, the second 100, as if we ordered the whole set and then got those 100.
Sure we don't need to sort everything. The (recursive) solution is this:
1. take a pivot value x
2. partition the records around the pivot, so there are k below x and N-k above x.
3. find where our required range (a..b) lies: if it is inside the whole partition, fine; repeat
4. otherwise, take some from the tail of the left partition and some from the head of the right partition.
That's it, right?
Complexity: average still O(n log(n)), but the worst case is O(n*(b-a)).
Right?
Sure we don't need to sort everything. The (recursive) solution is this:
1. take a pivot value x
2. partition the records around the pivot, so there are k below x and N-k above x.
3. find where our required range (a..b) lies: if it is inside the whole partition, fine; repeat
4. otherwise, take some from the tail of the left partition and some from the head of the right partition.
That's it, right?
Complexity: average still O(n log(n)), but the worst case is O(n*(b-a)).
Right?