Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use the basis of the quicksort algorithm to do what you need, except instead of reordering the partitions, you can get rid of the entries falling out of your desired range.</p> <p>It's been referred to as "quick select" and <a href="http://login2win.blogspot.com/2011/06/quick-select.html" rel="nofollow">here is a C++ implementation</a>:</p> <pre><code>int partition(int* input, int p, int r) { int pivot = input[r]; while ( p &lt; r ) { while ( input[p] &lt; pivot ) p++; while ( input[r] &gt; pivot ) r--; if ( input[p] == input[r] ) p++; else if ( p &lt; r ) { int tmp = input[p]; input[p] = input[r]; input[r] = tmp; } } return r; } int quick_select(int* input, int p, int r, int k) { if ( p == r ) return input[p]; int j = partition(input, p, r); int length = j - p + 1; if ( length == k ) return input[j]; else if ( k &lt; length ) return quick_select(input, p, j - 1, k); else return quick_select(input, j + 1, r, k - length); } int main() { int A1[] = { 100, 400, 300, 500, 200 }; cout &lt;&lt; "1st order element " &lt;&lt; quick_select(A1, 0, 4, 1) &lt;&lt; endl; int A2[] = { 100, 400, 300, 500, 200 }; cout &lt;&lt; "2nd order element " &lt;&lt; quick_select(A2, 0, 4, 2) &lt;&lt; endl; int A3[] = { 100, 400, 300, 500, 200 }; cout &lt;&lt; "3rd order element " &lt;&lt; quick_select(A3, 0, 4, 3) &lt;&lt; endl; int A4[] = { 100, 400, 300, 500, 200 }; cout &lt;&lt; "4th order element " &lt;&lt; quick_select(A4, 0, 4, 4) &lt;&lt; endl; int A5[] = { 100, 400, 300, 500, 200 }; cout &lt;&lt; "5th order element " &lt;&lt; quick_select(A5, 0, 4, 5) &lt;&lt; endl; } </code></pre> <p>OUTPUT:</p> <pre><code>1st order element 100 2nd order element 200 3rd order element 300 4th order element 400 5th order element 500 </code></pre> <p>EDIT</p> <p>That particular implementation has an O(n) average run time; due to the method of selection of pivot, it shares quicksort's worst-case run time. By <a href="http://en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithm_-_Median_of_Medians_algorithm" rel="nofollow">optimizing the pivot choice</a>, your worst case also becomes O(n).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload