Find top N elements in an Array

前端 未结 12 1233
南笙
南笙 2020-11-28 06:18

What would be the best solution to find top N (say 10) elements in an unordered list (of say 100).

The solution which came in my head was to 1. sort it using quick s

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 06:52

    public class FindTopValuesSelectionSortImpl implements FindTopValues {
    
    /**
     * Finds list of the highest 'n' values in the source list, ordered naturally, 
     * with the highest value at the start of the array and returns it 
     */
    @Override
    public int[] findTopNValues(int[] values, int n) {
        int length = values.length;
    
        for (int i=0; i<=n; i++) {
            int maxPos = i;
            for (int j=i+1; j values[maxPos]) {
                    maxPos = j;
                }
            }
    
            if (maxPos != i) {
                int maxValue = values[maxPos];
                values[maxPos] = values[i];**strong text**
                values[i] = maxValue;
            }           
        }
        return Arrays.copyOf(values, n);        
    }
    }
    

提交回复
热议问题