Sorting is an option due to additional memory. Consider the following algorithm.
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)
So this is step 4 (n * lg n), like sorting. The whole algorithm is n lg n and is very simple to encode.
Here is a quick and dirty example. It may contain errors, and, obviously, zero checks, etc. Get into the game.
import java.util.Arrays;
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 < 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 < orig.length; i++) { int onTrial = orig[i]; int index = Arrays.binarySearch(honey,onTrial); if(index < 0) continue; result[resultPos++] = i; } return result; } }
There are other things you can do to reduce the overhead of this operation. For example, instead of sorting, you can choose a queue that simply tracks the largest 5. Being int , their values should probably be boxed to be added to the collection (unless you flipped your own), which greatly increases overhead.
corsiKa
source share