Find top N elements in an Array

前端 未结 12 1231
南笙
南笙 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:39

    The best Algorithm would by large depend on the size of K. If K is small then by simply following BubbleSort Algorithm and iterating the outer loop K times would give the top K values. The complexity will be O(n*k).

    However for values of K close to n the complexity will approach O(n^2). In such scenario quicksort might be a good alternative.

提交回复
热议问题