nth element question

Jun 3, 2016 at 6:08pm
Hi,
Is this a correct description of nth_element() algorithm:

partially sorts [first,nth) so that for:

every i in [first,nth) and j in [nth,last)
*i <= *j


So [first,nthy) is sorted but the order of elements in [nth,last) is
not guaranteed

Is this correct? I have tried testing and it always seems to sort the whole collection - I guess it sometimes sorts [nth,last) as well but just does not
guarantee it right?

Thanks,
Juan
Last edited on Jun 3, 2016 at 6:09pm
Jun 3, 2016 at 7:30pm
nth_element is a quickselect algorithm -- it is very similar to quicksort, but it only sorts the partition with the target (nth) element.
https://en.wikipedia.org/wiki/Quickselect

Hope this helps.
Jun 3, 2016 at 7:38pm
http://www.cplusplus.com/reference/algorithm/nth_element/

I've never used it, but what I've read says that specific order is not guaranteed, except:
The element in the nth position will be the nth element
All elements [first, nth) will be <= than the nth element
All element (nth, last) will be >= nth

If all of the elements are sorted, that meets the requirements. The elements [first, nth) and (nth, last) are not guaranteed to be sorted.
Topic archived. No new replies allowed.