Possible Duplicate:
How to find the kth largest element in an unsorted array of length n in O(n)?
How do I write an algorithm to output the 10th highest number in an unsorted array of size n (in Java)?
Possible Duplicate:
How to find the kth largest element in an unsorted array of length n in O(n)?
How do I write an algorithm to output the 10th highest number in an unsorted array of size n (in Java)?
You are looking for selection algorithm, which can finds the kth biggest/smallest number in an array in O(n)
It can also be done using a partial sort, or using a min-heap of a fixed size k
, which will contain the k
th highest numbers at each time, and iterate the array while maintaining this heap.
Note that the last solution [min-heap] is less efficient then selection algorithm in terms of big O notation, for the general problem of an arbitrary k
.
Create an array of 10 elements. Keep the elements of your array sorted.
Passing through the original array once, compare the element with the smallest in your array of 10. If it is larger, put it in. Otherwise move on.
The best way is to use Prune and Search algorithm if the array does not containt discrete elements (is contains for example doubles). If is contains discrete elements (integers) - use Counting sort and pick 10th element)