Consider a situation like the following:
The array amounts
keeps track of some statistical amounts:
int[] amounts = { 1, 2, 5, 7, 2, 4, 8, 6 };
It is known that the array will always have a fixed size (in this case 8
). What I need to find are the indexes of a given number k
of smallest elements:
int k = 5;
int[] smallest = { 1, 2, 2, 4, 5 };
int[] smallestIndices = { 0, 1, 4, 5, 2 };
I figured I could make use of the Selection Algorithm, but I realized that this re-orders the array, thus returning an incorrect index.
Another idea I came up with was to create an array of tuples of index and value, and sort that array by the tuple value. Then I could extract the indexes of the first k
tuples in the sorted array. However, this seems like a wasteful solution that can probably done more easily.
Is there an algorithm that allows me to find the indexes of the k
smallest numbers in an array of size n
?
- Note that I am not looking for the smallest
k
numbers, which is already answered by this question. I am looking for their indexes. Thus, this question should not flagged as a duplicate.