Find top N elements in an Array

前端 未结 12 1273
南笙
南笙 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 07:00

    Written below both selection sort and insertion sort implementations. For larger data set I suggest insetion sort better than selection sort

    public interface FindTopValues
    {
      int[] findTopNValues(int[] data, int n);
    }
    

    Insertion Sort Implementation:

    public class FindTopValuesInsertionSortImpl 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=1; i 0) && (values[i] > values[curPos-1])) {
                curPos--;
            }
    
            if (curPos != i) {
                int element = values[i];
                System.arraycopy(values, curPos, values, curPos+1, (i-curPos));
                values[curPos] = element;
            }
        }       
    
        return Arrays.copyOf(values, n);        
    }   
    
    }
    

    Selection Sort Implementation:

    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];
                values[i] = maxValue;
            }           
        }
        return Arrays.copyOf(values, n);        
    }
    }
    

提交回复
热议问题