Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Sorting is an option, at the expense of extra memory. Consider the following algorithm.</p> <pre><code>1. Allocate additional array and copy into - O(n) 2. Sort additional array - O(n lg n) 3. Lop off the top k elements (in this case 5) - O(n), since k could be up to n 4. Iterate over the original array - O(n) 4.a search the top k elements for to see if they contain the current element - O(lg n) </code></pre> <p>So it step 4 is (n * lg n), just like the sort. The entire algorithm is n lg n, and is very simple to code.</p> <p>Here's a quick and dirty example. There may be bugs in it, and obviously null checking and the like come into play.</p> <p>import java.util.Arrays;</p> <pre><code>class ArrayTest { public static void main(String[] args) { int[] arr = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}; int[] indexes = indexesOfTopElements(arr,3); for(int i = 0; i &lt; indexes.length; i++) { int index = indexes[i]; System.out.println(index + " " + arr[index]); } } static int[] indexesOfTopElements(int[] orig, int nummax) { int[] copy = Arrays.copyOf(orig,orig.length); Arrays.sort(copy); int[] honey = Arrays.copyOfRange(copy,copy.length - nummax, copy.length); int[] result = new int[nummax]; int resultPos = 0; for(int i = 0; i &lt; orig.length; i++) { int onTrial = orig[i]; int index = Arrays.binarySearch(honey,onTrial); if(index &lt; 0) continue; result[resultPos++] = i; } return result; } } </code></pre> <p>There are other things you can do to reduce the overhead of this operation. For example instead of sorting, you could opt to use a queue that just tracks the largest 5. Being <code>int</code>s they values would probably have to be boxed to be added to a collection (unless you rolled your own) which adds to overhead significantly.</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. 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.
 

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