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

android - Pass an Serializable object in AIDL -

php - Improving script execution time -

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