Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Don't overestimate how big <code>log(M)</code> is, for a large list of length <code>M</code>. For a list containing a billion items, <code>log(M)</code> is only 30. So sorting and taking is not such an unreasonable method after all. In fact, sorting an array of integers is far faster thank sorting a list (and the array takes less memory also), so I would say that your best (brief) bet (which is safe for short or empty lists thanks to <code>takeRight</code>)</p> <pre><code>val arr = s.toArray java.util.Arrays.sort(arr) arr.takeRight(N).toList </code></pre> <p>There are various other approaches one could take, but the implementations are less straightforward. You could use a partial quicksort, but you have the same problems with worst-case scenarios that quicksort does (e.g. if your list is already sorted, a naive algorithm might be <code>O(n^2)</code>!). You could save the top <code>N</code> in a ring buffer (array), but that would require <code>O(log N)</code> binary search every step as well as <code>O(N/4)</code> sliding of elements--only good if <code>N</code> is quite small. More complex methods (like something based upon dual pivot quicksort) are, well, more complex.</p> <p>So I recommend that you try array sorting and see if that's fast enough.</p> <p>(Answers differ if you're sorting objects instead of numbers, of course, but if your comparison can always be reduced to a number, you can <code>s.map(x =&gt; /* convert element to corresponding number*/).toArray</code> and then take the winning scores and run through the list again, counting off the number that you need to take of each score as you find them; it's a bit of bookkeeping, but doesn't slow things down much except for the map.)</p>
    singulars
    1. This table or related slice is empty.
    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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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