algorithm - Adapting quickselect for smallest k elements in an array -


i know can kth order statistic (i.e. kth smallest number in array) using quickselect in linear time, if needed k smallest elements of array?

the wikipedia link has pseudocode single-element lookup, not k smallest elements lookup.

how should quickselect modified attain in linear time (if possible) ?

actually modifying quickselect not needed. if had array (called arraytosearch in example) , wanted k smallest items i'd this:

int i; int k = 10;  // if wanted 10 smallest elements  int smallestitems = new array(k); (i = 0; < k; i++) {     smallestitems[i] = quickselect(i, arraytosearch); } 

edit: under assumption k relatively small number make effective big-o o(n). if not assuming k small have speed of o(k*n), not linear time. answer easier comprehend, , applicable practical purposes. recursion.ninja's answer may more technically correct, , therefore better academic purposes.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -